pat1059. Prime Factors (25)

1059. Prime Factors (25)

时间限制
50 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
HE, Qinming

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 = p1^k1 * p2^k2 *…*pm^k(p1<p2<..pm-1<pm)  则从i=3开始循环,i依次增大,nn除以自己的质因数,不断减少。这里要注意,N最大的质因数可能只有一个,就是最后剩下的nn,这个需要判断。

 1 #include<cstdio>
 2 #include<stack>
 3 #include<cstring>
 4 #include<iostream>
 5 #include<stack>
 6 #include<set>
 7 #include<map>
 8 using namespace std;
 9 map<long long,int> fac;
10 int main(){
11     //freopen("D:\\INPUT.txt","r",stdin);
12     long long i,nn,n;
13     scanf("%lld",&nn);
14     if(nn==1){
15         printf("1=1\n");
16         return 0;
17     }
18     n=nn;
19     if(n%2==0){
20         fac[2]=1;
21         n/=2;
22         while(n%2==0){
23             fac[2]++;
24             n/=2;
25         }
26     }
27     for(i=3;i<n;i+=2){
28         if(n%i==0){
29             n/=i;
30             fac[i]=1;
31             while(n%i==0){
32                 n/=i;
33                 fac[i]++;
34             }
35         }
36     }
37     if(n!=1){
38         fac[n]=1;
39     }
40     printf("%lld=",nn);
41     map<long long,int>::iterator it=fac.begin();
42     printf("%lld",it->first);
43     if(it->second>1){
44         printf("^%d",it->second);
45     }
46     it++;
47     for(;it!=fac.end();it++){
48         printf("*%lld",it->first);
49         if(it->second>1){
50             printf("^%d",it->second);
51         }
52     }
53     printf("\n");
54     return 0;
55 }

 

posted @ 2015-09-02 00:25  Deribs4  阅读(232)  评论(0编辑  收藏  举报