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
注意n=1的情况!!!
#include <iostream> #include <map> #include <queue> #include <stdio.h> #include <vector> #include <algorithm> #include <stack> #include <stdlib.h> #include <string.h> #include <math.h> #include <string> using namespace std; #define N 10000 bool mark[N+1]; int prime[N+1]; int primesize; void init(){ primesize=0; for (int i=2;i<=N;i++) { if(mark[i]==true)continue; prime[primesize++]=i; for(int j=i*i;j<=N;j+=i){ mark[j]=true; } } } int main(){ init(); int n; int i; scanf("%d",&n); if (n==1) { printf("1=1"); return 0; } int m=n; int ansprime[30]; int anssize=0; int ansnum[30]; for( i=0;i<primesize;i++){ if(n%prime[i]==0){ ansprime[anssize]=prime[i]; ansnum[anssize]=0; while (n%prime[i]==0) { ansnum[anssize]++; n/=prime[i]; } anssize++; if(n==1)break; } } if(n!=1){ ansprime[anssize]=n; ansnum[anssize++]=1; } int ans=0; printf("%d=",m); for (i=0;i<anssize;i++) { if(i==0){ if(ansnum[i]==1) printf("%d",ansprime[i],ansnum[i]); else printf("%d^%d",ansprime[i],ansnum[i]); }else{ if(ansnum[i]==1) printf("*%d",ansprime[i],ansnum[i]); else printf("*%d^%d",ansprime[i],ansnum[i]); } } return 0; }