码迷,mamicode.com
首页 > 其他好文 > 详细

PAT1059. Prime Factors

时间:2015-02-21 11:59:24      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

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
思路:此题真是受益匪浅,首先需要观察素数表的打印,然后通过建立结构体进而来存储因子,而结构体中还可以存储数字。另外特殊的情况需要进行考虑。
技术分享
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cmath>
 4 using namespace std;
 5 #define MAX 100010
 6 struct Fraction
 7 {
 8     int num;
 9     int cnt;
10 } Frac[10];
11 bool Judge(int a)
12 {
13     if(a<=1)
14       return false;
15     int sqr= sqrt(a*1.0);
16     for(int i=2;i<=sqr;i++)
17     {
18         if(a%i==0)
19           return  false;
20     }
21     return true;
22 }
23 int prime[MAX]; 
24 void Init()
25 {
26     
27     //需要打印素数表
28     int npt=0;
29     for(int i=2;i<MAX;i++)
30     {
31         if(Judge(i))
32           prime[npt++]=i;
33     }
34 }
35 int main(int argc, char *argv[])
36 {
37     int n;
38     scanf("%d",&n);
39     printf("%d=",n);
40     Init();
41     int i=0;
42     int pt=0;
43     if(n==1)
44     {
45         printf("1\n");
46         return 0;
47     }
48     int sqr=sqrt(1.0*n);
49     for(int i=0;i<MAX&&prime[i]<=sqr;i++)
50     {
51         if(n%prime[i]==0)
52         {
53             Frac[pt].num=prime[i];
54             Frac[pt].cnt=0;
55             while(n%prime[i]==0)
56             {
57                 Frac[pt].cnt++;
58                 n/=prime[i];
59             }
60             pt++;
61         }
62     }
63     for(int i=0;i<pt;i++)
64     {
65         if(Frac[i].cnt!=0)
66         {
67             printf("%d",Frac[i].num);
68             if(Frac[i].cnt!=1)
69             {
70                 printf("^%d",Frac[i].cnt);
71             } 
72             if(i!=pt-1)
73                 putchar(*);
74                else if(n==1)
75                  putchar(\n);
76         }
77     }
78     if(n>1)
79     {
80         printf("%d\n",n);
81     }
82     return 0;
83 }
View Code

 

PAT1059. Prime Factors

标签:

原文地址:http://www.cnblogs.com/GoFly/p/4296902.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!