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

PAT 1059. Prime Factors (25)

时间:2015-08-12 23:16:27      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

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 = 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

以下算法可以改进为比3大的可以直接加2,忽略偶数
 1 #include <iostream>
 2 #include <vector>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     vector<int> factors, radix;
 9     long factor = 2;
10     long num;
11     cin >> num;
12     cout << num << "=";
13     if (num == 1)
14     {
15         cout << 1;
16         return 0;
17     }
18     while (num != 1)
19     {
20         int cnt = 0;
21         if (num % factor == 0)
22             factors.push_back(factor);
23         while (num%factor == 0)
24         {
25             cnt++;
26             num /= factor;
27         }
28         if (cnt!=0)
29             radix.push_back(cnt);
30         factor++;
31     }
32     
33     for (int i = 0; i < factors.size() - 1; i++)
34     {
35         cout << factors[i];
36         if (radix[i]>1)
37             cout << "^" << radix[i];
38         cout << "*";
39     }
40     cout << factors.back();
41     if (radix.back() > 1)
42         cout << "^" << radix.back();
43 }

 

PAT 1059. Prime Factors (25)

标签:

原文地址:http://www.cnblogs.com/jackwang822/p/4725711.html

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