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 }
1 #include<iostream> 2 using namespace std; 3 bool isPrime(long int num){ 4 if(num<2) return false; 5 for(int i=2; i*i<num+1; i++) 6 if(num%i==0) return false; 7 return true; 8 } 9 int main(){ 10 long int num,i; 11 cin>>num; 12 if(num==1){cout<<"1=1";return 0;}//特俗处理数字1 13 cout<<num<<"="; 14 bool flag=true;//标记是否已经输出第一个元素 15 for(i=2; i<=num; i++){ 16 int cnt=0; 17 if(isPrime(i)){ 18 while(num%i==0){//计算该质数因子的指数 19 num/=i; 20 cnt++; 21 } 22 if(cnt!=0){//如果该质数是因子,输出该因子 23 if(flag){ 24 cout<<i; 25 flag = false; 26 }else cout<<"*"<<i; 27 if(cnt>1) cout<<"^"<<cnt;} 28 } 29 } 30 return 0; 31 }