PAT 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\

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 struct node{
 5   int x, cnt;
 6 }f[40];
 7 
 8 int prime[100010], vis[100010]={0}, pNum=0, cnt=0;
 9 void getPrime(){
10   for(int i=2; i<100010; i++){
11     if(!vis[i]){
12       prime[pNum++] = i;
13       for(int j=i+i; j<100010; j += i) vis[j]=1;
14     }
15   }
16 }
17 
18 void factor(long n){
19   for(int i=0; i<pNum && n!=1; i++){
20       if(n%prime[i]==0){
21         f[cnt].cnt=0;
22         while(n%prime[i]==0){
23             f[cnt].cnt++;
24             f[cnt].x=prime[i];
25             n /= prime[i];
26         }
27         cnt++;
28       }
29   }
30   if(n!=1){
31     f[cnt].x=n;
32     f[cnt].cnt=1;
33   }
34 }
35 int main(){
36   long int n, i;
37   cin>>n;
38   getPrime();
39   factor(n);
40   if(n==1){ cout<<"1=1"<<endl; return 0;}
41   printf("%d=", n);
42   for(i=0; i<cnt; i++){
43     if(i>0) printf("*");
44     printf("%d", f[i].x);
45     if(f[i].cnt>1) printf("^%d", f[i].cnt);
46   }
47   return 0;
48 }
 

猜你喜欢

转载自www.cnblogs.com/mr-stn/p/9225971.html