首页 > 其他 > 详细

1059. Prime Factors (25)

时间:2015-12-06 12:57:55      阅读:177      评论: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 <vector>
  3. using namespace std;
  4. vector<long int> factor;
  5. vector<long int> exponent;
  6. bool isPrime(long int a) {
  7. if (a == 2 || a == 3)
  8. return true;
  9. for (long int i = 2; i*i < a; i++)
  10. if (a%i == 0)
  11. return false;
  12. return true;
  13. }
  14. int main(void) {
  15. long int n;
  16. cin >> n;
  17. cout << n << "=";
  18. if (n < 2) {
  19. cout << n;
  20. return 0;
  21. }
  22. long int i = 2;
  23. while (true)
  24. {
  25. if (!isPrime(i)) {
  26. i++;
  27. continue;
  28. }
  29. if (n%i == 0) {
  30. int expCnt = 0;
  31. factor.push_back(i);
  32. while (true)
  33. {
  34. if (n%i == 0) {
  35. n = n / i;
  36. expCnt++;
  37. }
  38. else {
  39. exponent.push_back(expCnt);
  40. break;
  41. }
  42. }
  43. }
  44. i++;
  45. if (n == 1) {
  46. break;
  47. }
  48. }
  49. for (int i = 0; i < exponent.size(); i++) {
  50. if (exponent[i] == 1)
  51. cout << factor[i];
  52. else
  53. cout << factor[i] << "^" << exponent[i];
  54. if (i != exponent.size() - 1)
  55. cout << "*";
  56. }
  57. return 0;
  58. }





1059. Prime Factors (25)

原文:http://www.cnblogs.com/zzandliz/p/5023191.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!