1. 程式人生 > >1059 Prime Factors (25 分)水

1059 Prime Factors (25 分)水

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 = p​1​​​k​1​​​​×p​2​​​k​2​​​​×⋯×p​m​​​k​m​​​​.

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 = p​1​​^k​1​​*p​2​​^k​2​​**p​m​​^k​m​​, where p​i​​'s are prime factors of N in increasing order, and the exponent k​i​​ is the number of p​i​​ -- hence when there is only one p​i​​, k​i​​ is 1 and must NOT be printed out.

Sample Input:

97532468

Sample Output:

97532468=2^2*11*17*101*1291

程式碼

#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e5+10; 
typedef long long ll;
ll pri[maxn];
vector<ll>vec; 
void init()
{
	pri[1] = 1;
	vec.push_back(1); 
	for(ll i = 2; i < 500000; i++)
    {
    	if(pri[i] == 0 )
		{
			for(ll j = i + i; j < 500000; j += i)
            	pri[j] = 1;
            vec.push_back(i);
		}	
	}    
	return;
}    
int main()
{
	init();
	ll n;
	scanf("%lld",&n);
	ll size = vec.size();
	printf("%lld=",n);
	for(ll i = 0 ; i < size; i ++)
	{
		if(vec[i] == n)
		{
			printf("%lld\n",n);
			return 0;
		}	
	}
	ll k = n;
	int flag = 0;
	bool state = false;
	for(ll i = 1; i < size && k >= 2; i ++)
	{
		ll cnt = 0;
		while(k % vec[i] == 0)
		{
			cnt ++;
			k = k / vec[i];
		}
		if(cnt >= 1)
		{
			if(state) printf("*");
			printf("%lld",vec[i]);
			if(cnt >= 2)
				printf("^%lld",cnt);
			state = true;
		}
	}
	printf("\n");
    return 0;
}