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
#include<iostream>
using namespace std;
int main()
{
	long long n;
	cin>>n;
	long long int i = 2;
	int count = 0;
	cout<<n<<'=';
	if(n == 1) // 这一段代码非常重要 ,需要考虑n=1的情况 
	{
		cout<<1;
		return 0;	
	}	
	while(n)
	{
		if(n % i == 0)
		{
			n = n / i;
			count++;
		}
		else
		{
			if(count == 1)
			{
				cout<<i;
			}
			else if(count > 1)
			{
				cout<<i<<'^'<<count;
			}
			if(count != 0)
			{
				if(n != 1)
					cout<<'*';
				if(n == 1)
					break;
			}
			count = 0;
			i++;
			if(i % 2 == 0)
			i++;
			
		}
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/Easadon/article/details/79942943