1059. Prime Factors (25)

题目:

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1^k1* p2^k2 *…*pm^km.

Input Specification:

Each input file contains one test case which gives a positive integer N in the range of long int.

Output Specification:

Factor N in the format N = p1^k1 * p2^k2 *…*pm^km, where pi's are prime factors of N in increasing order, and the exponent ki is the number of pi -- hence when there is only one pi, ki is 1 and must NOT be printed out.

Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
注意:
1、据说人生就是不停地写代码,这里就是不停地找最小的那个质数因子,然后除去这个质数因子,至死方休。
2、小心地输出结果就好了。

代码:
#include<iostream>
#include<cmath>
using namespace std;

bool isPrime(long t)
{
	long up =sqrt((long double)t);
	for(int i=2;i<=up;++i)
		if(t%i==0)
			return false;
	return true;
}

int main()
{
	long n;
	scanf("%ld",&n);
	printf("%d=",n);
	int cur=0,k=0;
	while(!isPrime(n))
	{
		long up=sqrt((long double)n);
		for(long i=2;i<=up;++i)
		{//find the smallest factor for n
			if(isPrime(i) && n%i==0)
			{
				if(i!=cur)
				{//if i is a new factor
					if(k>1) printf("^%d",k);
					if(k!=0) printf("*");//if it isn't the first factor
					printf("%d",i);
					k=1;cur=i;
				}
				else
					++k;
				n /= i;
				break;
			}
		}
	}
	if(cur==n)
		printf("^%d\n",++k);
	else
	{
		if(k!=0) printf("*");//if it isn't the first factor
		printf("%d",n);
	}
	return 0;
}

你可能感兴趣的:(考试,pat,浙江大学)