Exemplo n.º 1
0
static int approach1(const int upTo) {
	decltype(primeFactors(0)) commonFactors, temp;
	temp.reserve(64);

	// LCD = product of common factors of 2...X
	for (int p = 2; p <= upTo; p++) {
		auto factors = primeFactors(p);
		temp.clear();
		
		// merge common factors
		std::set_union(commonFactors.begin(), commonFactors.end(), factors.begin(), factors.end(), std::back_inserter(temp));
		std::swap(commonFactors, temp);
	}
	
	return std::accumulate(commonFactors.begin(), commonFactors.end(), 1, std::multiplies<uint64_t>());
}
Exemplo n.º 2
0
int main(int argc, const char * argv[]) {
	// prime the primes
	primeFactors(63);

	// approach 1 uses the common prime factorization technique
	{
		TimedBlock _("a1-10");
		std::cout << "approach1(10) = " << approach1(10) << "\n";
	}
	{
		TimedBlock _("a1-20");
		std::cout << "approach1(20) = " << approach1(20) << "\n";
	}
	std::cout << "---------------\n";

	// approach 2 uses the lcd(a,b) = (a/gcd(a,b))*b principle
	{
		TimedBlock _("a2-10");
		std::cout << "approach2(10) = " << approach2(10) << "\n";
	}
	{
		TimedBlock _("a2-20");
		std::cout << "approach2(20) = " << approach2(20) << "\n";
	}
}
Exemplo n.º 3
0
std::vector<unsigned long long> primeFactors(unsigned long long n) {
  bool found = false;

  unsigned long long v = 2;

  for (unsigned long long i = 2; i < n - 1; i++) {
    if (n % i == 0) {
      found = true;

      v = i;

      break;
    }
  }

  std::vector<unsigned long long> result;

  if (found) {
    result.push_back(v);

    std::vector<unsigned long long> moreFactors = primeFactors(n / v);

    result.insert(result.end(), moreFactors.begin(), moreFactors.end());
  } else {
    result.push_back(n);
  }

  return result;
}
Exemplo n.º 4
0
int main(int argc, const char * argv[]) {
    
    
    int number;

    //loop until zero is end to end the program
    do {
       
      printf("1. Factors \n");
      printf("2. Prime Factors \n");
      printf("0. Stop \n");
        
      scanf("%d", &number);
        
        
        if (number == 1) {
            factors();
        }
        
        if (number == 2) {
            primeFactors();
        }
        
        
        
    } while (number != 0);
    
    
}
Exemplo n.º 5
0
//test function
 int main()
{
    
    //very large n
    unsigned long long int n = 987654321;
  
    std::cout<< "The factors for 987654321= "; 
    primeFactors(n);
    std::cout<<std::endl;
    
    //another n
    n = 11111111111;
    std::cout<< "The factors for 11111111111= "; 
    primeFactors(n);
    std::cout<<std::endl;
    return 0;
}
Exemplo n.º 6
0
static uint64_t approach1(const uint64_t num) {
	auto factors = primeFactors(num);
	
	std::ostream_iterator<uint64_t> osi(std::cout, " ");
	copy(factors.begin(), factors.end(), osi);
	std::cout << '\n';

	return factors.back();
}
Exemplo n.º 7
0
int main()
{
    int i,j,x,y,counter1=0,counter2=0,value;
    primeFactors(2334530,first);
    for(i=0;first[i]!='\0';i++)
		printf("%d ",first[i]);
	printf("\n\n");	
	primeFactors(58080*5*3*3,second);
    for(i=0;second[i]!='\0';i++)
		printf("%d ",second[i]);
	
	i=0,j=0;
	while(second[i]!='\0'){
		if(second[i]==second[i+1]){
			//printf("\nBoth are equal\n");
			second[j]=second[j]*second[i+1];
			i++;
			//continue;
		}
		else{
			second[++j]=second[++i];
		}
	}
	second[j]='\0';
	printf("\n\n");
	for(i=0;second[i]!='\0';i++)
		printf("%d ",second[i]);
		
    return 0;
    
    for(i=1;;i++){
		j=i+1;
		primeFactors(i,first);
		primeFactors(j,second);
		
	}
    
    return 0;
}
Exemplo n.º 8
0
	int main() {
	int n;
	
		while(1){
			scanf("%d",&n);
		printf("main");
			
			if(n==0)break;
		
			
			int y =n;
			if (n<0){
				printf("%d = -1 x ",n);
				primeFactors(y);
			}else {
				printf("%d = ",n);
				primeFactors(-y);
				}
			
			
		}
		return 0;
	}
Exemplo n.º 9
0
void* scan(void* param) {
	scanargs* args = (scanargs*)param;
	result *res = (result*)malloc(sizeof(result));
	res->count = 0;
	res->index = 0;
	
	int i,p;
	for (i = args->start; i<=args->stop; i++) {
		p = primeFactors(args->array[i]);
		//printf("number: %d ; primes: %d ; index: %d\n", args->array[i],p,i);
		if (p>res->count) {
			res->count = p;
			res->index = i;
		}
	}
	pthread_exit((void*)res);
}
Exemplo n.º 10
0
void precal()
{
   int i,j,y=0;
    for(i=1;i<=1005;i++)
    {
        for(j=y+1;j<=1000000;j++)
        {
            int x=primeFactors(j);
            if(x>=3)
            {
                a[i]=j;
                y=j;
                break;

            }
        }

    }
}
int main(){
    int t,n,temp,prod,i,ans,count;
	scanf("%d",&t);
	while(t--){
		for(i=0;i<1000000;i++)
			a[i]=0;
		prod=1;
		scanf("%d",&n);
		for(i=0;i<n;i++)
        {
			scanf("%d",&temp);
			primeFactors(temp);
		}
		ans=1;
		count=1;
	for(i=0;i<1000000;i++)
		ans=ans*(a[i]+1);
		printf("%d\n",ans);
	}	
	return 0;
}
Exemplo n.º 12
0
int main() {
  unsigned long long n = 1;

  unsigned long long numberOfDivisors = 0;

  unsigned long long triangleNumber;

  while(numberOfDivisors < 500) {
    n++;

    triangleNumber = 0;

    for (unsigned long long i = 1; i <= n; i++) {
      triangleNumber += i;
    }

    std::vector<unsigned long long> factors = primeFactors(triangleNumber);

    std::map<unsigned long long, unsigned long long> factorLengths;

    std::for_each(factors.begin(), factors.end(), [&](const unsigned long long factor){
      factorLengths[factor] = 0;
    });

    std::for_each(factors.begin(), factors.end(), [&](const unsigned long long factor){
      factorLengths[factor]++;
    });

    numberOfDivisors = 1;

    std::for_each(factorLengths.begin(), factorLengths.end(), [&](const std::pair<unsigned long long, unsigned long long>& pair){
      numberOfDivisors *= pair.second + 1;
    });
  }

  std::cout << triangleNumber << std::endl;

  return 0;
}
Exemplo n.º 13
0
/* Driver program to test above function */
int main()
{
    int n = 31;
    primeFactors(n);
    return 0;}
Exemplo n.º 14
0
Number& Root::simplify(){
	if (typeid(*base) == typeid(Integer) && typeid(*root) == typeid(Integer)) {
		Integer * baseInt = dynamic_cast<Integer*>(base);
		Integer * rootInt = dynamic_cast<Integer*>(root);

		bool isRootNeg = false;
		bool isBaseNeg = false;

		if (rootInt->getInt() < 0) {
			isRootNeg = true;
			int newRoot = rootInt->getInt() * -1;
			delete rootInt;
			root = new Integer(newRoot);
			rootInt = new Integer(newRoot);
		}
		else if (rootInt->getInt() == 0) {
			throw std::out_of_range("The value of n for an n'th root object cannot be 0. SOURCE: " + this->toString());
		}

		if (baseInt->getInt() < 0 && rootInt->getInt() % 2 != 0) {
			isBaseNeg = true;
			int newBase = baseInt->getInt() * -1;
			delete baseInt;
			base = new Integer(newBase);
			baseInt = new Integer(newBase);
		}
		else if (baseInt->getInt() == 0) {
			return *(new Integer(0));
		}
		else if (baseInt->getInt() < 0 && rootInt->getInt() % 2 == 0) {
			throw std::out_of_range("A negative number cannot be applied to an even root. SOURCE: " + this->toString());
		}
		
		std::vector<int*> vec = primeFactors(baseInt->getInt());

		double invRoot = 1 / ((double)rootInt->getInt());

		if ((int)pow(baseInt->getInt(), invRoot) == pow(baseInt->getInt(), invRoot)) {
			if (isRootNeg) {
				Integer * one = new Integer(1);
				Placeholder * ph = new Placeholder();
				ph->getNumbers().push_back(one);
				if (isBaseNeg) {
					ph->getNumbers().push_back(new Integer(pow(baseInt->getInt(), invRoot) * -1));
				}
				else {
					ph->getNumbers().push_back(new Integer(pow(baseInt->getInt(), invRoot)));
				}
				ph->getOperators().push_back('/');
				return *ph;
			}
			if (isBaseNeg) {
				Number * toReturn = (new Integer(pow(baseInt->getInt(), invRoot) * -1));
				return *toReturn;
			}
			else {
				Number * toReturn = (new Integer(pow(baseInt->getInt(), invRoot)));
				return *toReturn;
			}
		}

		int multiplier = 1;
		int innerValue = 1;

		for (int i = 1; i < vec.size(); i++) {
			int exp = vec.at(i)[1];
			int multiplierExp = 0;
			for (int x = 0; x < vec.at(i)[1]; x++) {
				if (exp - rootInt->getInt() >= 0) {
					exp = exp - rootInt->getInt();
					multiplierExp++;
				} else {
					x = vec.at(i)[1];
				}
			}

			vec.at(i)[1] = exp;
			multiplier *= pow(vec.at(i)[0], multiplierExp);
			innerValue *= pow(vec.at(i)[0], vec.at(i)[1]);
		}

		if (multiplier > 1) {
			if (innerValue == 1) {
				Number * toReturn = new Integer(multiplier);
				return *toReturn;
			}

			if (isRootNeg) {
				Integer * one = NULL;

				if (isBaseNeg) {
					one = new Integer(1);
				}
				else {
					one = new Integer(-1);
				}

				Placeholder * simplified = new Placeholder();
				simplified->getNumbers().push_back(new Integer(multiplier));
				delete base;
				this->base = new Integer(innerValue);
				simplified->getNumbers().push_back(&this->clone());
				simplified->getOperators().push_back('*');

				Placeholder * ph = new Placeholder();
				ph->getNumbers().push_back(one);
				ph->getNumbers().push_back(simplified);
				ph->getOperators().push_back('/');
				return *ph;
			}

			Placeholder * simplified = new Placeholder();
			if (isBaseNeg) {
				simplified->getNumbers().push_back(new Integer(multiplier * -1));
			}
			else {
				simplified->getNumbers().push_back(new Integer(multiplier));
			}
			delete base;
			this->base = new Integer(innerValue);
			simplified->getNumbers().push_back(&this->clone());
			simplified->getOperators().push_back('*');
			return *simplified;
		}

		return this->clone();
	} else if (typeid(*root) == typeid(Placeholder)) {
		Placeholder * rootPlaceholder = dynamic_cast<Placeholder*>(root);
		if (typeid(rootPlaceholder->getNumbers().at(0)) == typeid(Integer)) {
			Integer * negRootInt = dynamic_cast<Integer*>(rootPlaceholder->getNumbers().at(0));
			Integer * rootInt = dynamic_cast<Integer*>(rootPlaceholder->getNumbers().at(1));
			if (negRootInt->getInt() == -1) {
				Placeholder * ph = new Placeholder();
				Integer * one = new Integer(1);

				ph->getNumbers().push_back(one);
				ph->getNumbers().push_back(&rootInt->clone());
				ph->getOperators().push_back('/');
				Exponent * exp = new Exponent(base->clone(), *ph);
				return *exp;
			} else {
				return this->clone();
			}
		} else {
			return this->clone();
		}
	} else if (typeid(*base) == typeid(Placeholder)) {
		Placeholder * basePlaceholder = dynamic_cast<Placeholder*>(base);
		if (typeid(basePlaceholder->getNumbers().at(0)) == typeid(Integer)) {
			Integer * negBaseInt = dynamic_cast<Integer*>(basePlaceholder->getNumbers().at(0));
			if (typeid(*root) == typeid(Integer)) {
				Integer * rootInt = dynamic_cast<Integer*>(root);
				if (negBaseInt->getInt() < 0 && rootInt->getInt() % 2 == 0) {
					throw std::out_of_range("A negative number cannot be applied to an even root. SOURCE: " + this->toString());
				}
			}
		}
	} else {
		return this->clone();
	}
}
Exemplo n.º 15
0
s64 s(s64 n, const QVector<s64>& primes) {
    return s(primeFactors(n, primes));
}
Exemplo n.º 16
0
static int math_read(const char *path, char *buf, size_t size, off_t offset,
		      struct fuse_file_info *fi)
{
	printf("read(\"%s\"\n", path);

	size_t len;
	(void) fi;
	memset(buf, 0, sizeof(buf));
	
	/* build the documentation for each operation */
	if(strcmp(path, adddoc_path) == 0)
	{
		len = strlen(add_str);	
		if (offset < len) {
			if (offset + size > len)
				size = len - offset;
			memcpy(buf, add_str + offset, size);
		} else
			size = 0;
	}		
	else if(strcmp(path, subdoc_path) == 0)
	{
		len = strlen(sub_str);	
		if (offset < len) {
			if (offset + size > len)
				size = len - offset;
			memcpy(buf, sub_str + offset, size);
		} else
			size = 0;
	}
	else if(strcmp(path, muldoc_path) == 0)
	{
		len = strlen(mul_str);	
		if (offset < len) 
		{
			if (offset + size > len)
				size = len - offset;
			memcpy(buf, mul_str + offset, size);
		} else
			size = 0;
	}
	else if(strcmp(path, divdoc_path) == 0)
	{
		len = strlen(div_str);	
		if (offset < len) {
			if (offset + size > len)
				size = len - offset;
			memcpy(buf, div_str + offset, size);
		} else
			size = 0;
	}
	else if(strcmp(path, expdoc_path) == 0)
	{
		len = strlen(exp_str);	
		if (offset < len) {
			if (offset + size > len)
				size = len - offset;
			memcpy(buf, exp_str + offset, size);
		} else
			size = 0;
	}
	
	else if(strcmp(path, facdoc_path) == 0)
	{
		len = strlen(fac_str);	
		if (offset < len) {
			if (offset + size > len)
				size = len - offset;
			memcpy(buf, fac_str + offset, size);
		} else
			size = 0;
	}
	else if(strcmp(path, fibdoc_path) == 0)
	{
		len = strlen(fib_str);	
		if (offset < len) {
			if (offset + size > len)
				size = len - offset;
			memcpy(buf, fib_str + offset, size);
		} else
			size = 0;
	}
	
	/* add, sub, mul, div, exp operations, 
	 * compute and dump the result into buf*/
	else if(strcmp(path, Path2) == 0)
	{
		double d[2];
		double result;
		char buffer[Path_size];
		
		d[0] = strtod (arg[1], NULL);
		d[1] = strtod (arg[2], NULL);
		
		if (strncmp(path, add_path, 4) == 0)
		{
			result = d[0] + d[1];
			sprintf(buffer, "%lf\n", result);
		}
		else if (strncmp(path, sub_path, 4) == 0)
		{
			result = d[0] - d[1];
			sprintf(buffer, "%lf\n", result);
		}
		else if (strncmp(path, mul_path, 4) == 0)
		{
			result = d[0] * d[1];
			sprintf(buffer, "%lf\n", result);
		}
		else if (strncmp(path, div_path, 4) == 0)
		{
			/* check if the divisor is 0 */
			if(d[1] != 0)
			{
				result = d[0] / d[1];
				sprintf(buffer, "%lf\n", result);
			}
			else
				strcpy(buffer, "divide by zero error\n");
		}
		else if (strncmp(path, exp_path, 4) == 0)
		{
			result = pow(d[0], d[1]);
			sprintf(buffer, "%lf\n", result);
		}

		/* get the length of the string, dump it into bug */
		len = strlen(buffer);		
		if (offset < len) 
		{
			if (offset + size > len)
				size = len - offset;
			memcpy(buf, buffer + offset, size);
		} else
			size = 0;
	}
	
	/* fib, fac operations, 
	 * compute and dump the result into buf*/
	if(strcmp(path, Path1) == 0)
	{
		Array f;				
		double d;
		int i;
		char buffer[FILESIZE];		
		initArray(&f,1);		
		
		d = strtod (arg[1], NULL);
		memset(buffer, 0, sizeof(buffer));
		char tempbuf[100];
		
		if (strncmp(path, fib_path, 4) == 0)
		{
			/* check if input number is a positve integer */
			if (IsInt(d) && d >= 1)
			{
				Fibonacci(&f, d);
				printArray(&f);
				
				/* put fibonacci numbers into one buffer*/
				for (i=0; i < (&f)->used; i++)
				{
					sprintf(tempbuf, "%"PRIu64"\n", (&f)->array[i]) ;
					strcat(buffer, tempbuf);				
				}
				
			}
			else
				strcpy(buffer, "Only integers that are larger than 1 have prime factors.\n");
			
			/* get the length of the string, dump it into buf */	
			len = strlen(buffer);			
			if (offset < len)
			{
				if (offset + size > len)
					size = len - offset;
				memcpy(buf, buffer + offset, size);
			} 
		}
		else if (strncmp(path, fac_path, 4) == 0)
		{
			/* check if the input number is a integer > 2*/
			if (IsInt(d) && d > 2)
			{
				primeFactors(&f, d);
				for (i=0; i < (&f)->used; i++)
				{
					sprintf(tempbuf, "%"PRIu64"\n", (&f)->array[i]) ;
					strcat(buffer, tempbuf);				
				}
			}
			else 
				strcpy(buffer, "Error. Only positive integer is expected.\n");
			/* get the length of the string, dump it into buf */
			len = strlen(buffer);			
			if (offset < len) 
			{
				if (offset + size > len)
					size = len - offset;
				memcpy(buf, buffer + offset, size);
			} 
		}
		
		
		else
			size = 0;
		freeArray(&f);
	}

	return size;
}
Exemplo n.º 17
0
int main (int argc, char* argv[]) {
	
	timer *t = timer_alloc();
	recorder *thread_rec = recorder_alloc("thread.csv");
	recorder *proc_rec = recorder_alloc("proc.csv");
	// on init tous les `recorders` et le timer
	
	srand (1337);
	int* array = (int*)malloc(sizeof(int)*NLENGTH);
	if (array == NULL) err(1,"erreur malloc");
	int i;
	for (i=0; i<NLENGTH; i++) {
		array[i] = rand() % NLENGTH;
	}
	// on génère le tableau de int aléatoires
	
	
	/*
	 *  _______ _                        _
	 * |__   __| |                      | |
	 *    | |  | |__  _ __ ___  __ _  __| |___
	 *    | |  | '_ \| '__/ _ \/ _` |/ _` / __|
	 *    | |  | | | | | |  __/ (_| | (_| \__ \
	 *    |_|  |_| |_|_|  \___|\__,_|\__,_|___/
     */
	
	for (i = 1; i<=NTHREAD; i=i+1) {
		start_timer(t);
		// on lance le chronomètre
		int error = 0;
		
		pthread_t* threads = (pthread_t*)malloc(sizeof(pthread_t)*i);
		if (threads == NULL) err(1,"erreur malloc");
		scanargs** args = (scanargs**)malloc(sizeof(scanargs*)*i);
		if (args == NULL) err(1,"erreur malloc");
		result* res[i];
		// init des tableaux d'arguments, de threads, et de resultats
		
		int j;
		for (j=0; j<i; j++) {
			args[j] = (scanargs*)malloc(sizeof(scanargs));
			if (args[j] == NULL) err(1,"erreur malloc");
			args[j]->start = j*(NLENGTH/i);
			args[j]->stop = (j+1)*(NLENGTH/i)-1;
			args[j]->array = array;
			// remplissage de la structure argument avec le segment à scanner par le thread
			error = pthread_create(&threads[j],NULL,&scan,(void*)args[j]);
			if(error!=0) err(error,"erreur create");
			// lancement du thread
		}
		
		for (j=0; j<i; j++) {
			error=pthread_join(threads[j],(void**)&res[j]);
			if(error!=0) err(error,"erreur create");
			// join du thread et réception de la structure resultat
		}
		
		/*
		 * Analyse des resultats de tous les threads
		 */
		int index = -1;
		int max = 0;
		for (j=0; j<i; j++) {
			if (max<res[j]->count) {
				max = res[j]->count;
				index = res[j]->index;
				free(res[j]);
				free(args[j]);
			}
		}
		
		printf("%d\n",index);
		write_record_n(thread_rec,i,stop_timer(t),NTHREAD);
		//sauvegarde du temps
		
		free(threads);
		free(args);
	}
	
	puts("proc");
	
	/*
	 *  _____
	 * |  __ \
	 * | |__) | __ ___   ___ ___  ___ ___  ___  ___
	 * |  ___/ '__/ _ \ / __/ _ \/ __/ __|/ _ \/ __|
	 * | |   | | | (_) | (_|  __/\__ \__ \  __/\__ \
	 * |_|   |_|  \___/ \___\___||___/___/\___||___/
     *
	 *
	 * Meme chose que les threads mais avec des processus cette fois ci
	 */
	
	for (i = 1; i<=NTHREAD; i=i+1) {
		
		start_timer(t);
		int error = 0;
		pid_t pid[i];
		int fd[i][2];
		
		int j;
		for (j=0; j<i; j++) {
			int start = j*(NLENGTH/i);
			int stop = (j+1)*(NLENGTH/i)-1;
			// on définit le segment à scanner
			pipe(fd[j]);
			// on init le pipe entre le père et fils. Il sert à ce que le fils renvoie sa réponse au père
			pid[j] = fork();
			
			if (pid[j] == 0) {
				// on est dans le fils
				int k,p,index,count=0;
				for (k = start; k<=stop; k++) {
					p = primeFactors(array[k]);
					//printf("number: %d ; primes: %d ; index: %d\n", args->array[i],p,i);
					if (p>count) {
						count = p;
						index = k;
					}
				}
				
				//printf("index: %d count: %d\n",index,count);
				
				index = index*1000;
				index += count;
				// vu qu'on a 2 int à renvoyer, on les combine en 1 int à déchiffre par le père
				//printf("index: %d\n",index);
				
				close(fd[j][0]);
				write(fd[j][1], &index, sizeof(index));
				// envoie de la réponse par pipe
				close(fd[j][1]);
				
				exit(0);
			} else if (pid[j] < 0) {
				err(-1,"erreur de fork");
			}
		}
		int max = 0,index,ret;
		for (j=0; j<i; j++) {
			
			close(fd[j][1]);
			read(fd[j][0], &ret, sizeof(ret));
			//réception de la réponse des fils
			close(fd[j][0]);
			
			pid[j] = waitpid(pid[j],NULL,0);
			if(pid[j]<1)err(-1,"erreur waitpid");
			//printf("ret: %d\n",ret);
			//analyse des résultats
			if (max < ret%1000) {
				max = ret%1000;
				index = ret/1000;
			}
		}
		
		printf("%d\n",index);
	    /*
		 *int it = i;
		 *int numCPU = sysconf( _SC_NPROCESSORS_ONLN );
		 *if (it > numCPU ) it = numCPU;
		 */
		write_record_n(proc_rec,i,stop_timer(t),NTHREAD);
		// ecriture du temps
	}
	
	recorder_free(thread_rec);
	recorder_free(proc_rec);
	timer_free(t);
	free(array);
	// free de nos structures
}