PAT甲级1059

1059. Prime Factors (25)

时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
HE, Qinming

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

#include
#include
#include
#include
using namespace std;
int prime = 2;
struct PrimeFactor
{
	int p, k;
	PrimeFactor():k(0){}
};
bool isPrime(int a)
{
	if (a < 2)
		return false;
	int t = sqrt(a);
	for (int i = 2; i <= t; i++)
	{
		if (a%i == 0)
			return false;
	}
	return true;
}
int nextPrime()
{
	while (!isPrime(prime))
	{
		prime++;
	}
	int temp = prime;
	prime++;
	return temp;
}
int main()
{
	vector v;
	int N;
	scanf("%d", &N);
	if (N == 1)//特判
	{
		printf("%d=%d", N, N);
		return 0;
	}
	int n = N;
	PrimeFactor pf;
	if (isPrime(N))//对质数的特判
	{
		printf("%d=%d", N, N);
		return 0;
	}
	else
	{
		do
		{
			pf.p = nextPrime();
			pf.k = 0;
			while (1)
			{
				if (N%pf.p == 0)
				{
					N /= pf.p;
					pf.k++;
				}
				else
					break;
			}
			if(pf.k)//只有k不为0时才加入容器
			v.push_back(pf);
			if (isPrime(N))
			{
				pf.p = N;
				pf.k = 1;
				v.push_back(pf);
				break;
			}
		} while (N!=1);//这里注意while循环终止不是N==0而是N==1,别惯性思维
	}
	printf("%d=", n);
	for (int i = 0; i < v.size(); i++)
	{
		printf("%d", v[i].p);
		if (v[i].k > 1)
			printf("^%d", v[i].k);
		if (i != v.size() - 1)
			printf("*");
	}
	return 0;
}
/*代码是否能完整反映自己的思想,这一点得反复斟酌,自己模拟简单实例追溯程序过程验证程序可靠性*/

你可能感兴趣的:(PAT)