(PAT 1059) Prime Factors (分解质因子)

向右看齐 2022-03-18 02:48 332阅读 0赞

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1k1×p2k2×⋯×pmkm.

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:

  1. 97532468

Sample Output:

  1. 97532468=2^2*11*17*101*1291

解题思路:

分解质因子即可

这里1需要特判处理,因为程序不会输出1,所以如果输入的数字为1,那么就输出1=1

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <math.h>
  4. using namespace std;
  5. const int MAXN = 100010;
  6. long long primelist[MAXN];
  7. long long objNum;
  8. int num;
  9. int index = 0;
  10. struct factor {
  11. long long x, cnt;
  12. }facs[MAXN];
  13. bool isprime(long long num) {
  14. if (num <= 1) return false;
  15. for (long long i = 2; i*i <= num; ++i) {
  16. if (num % i == 0) return false;
  17. }
  18. return true;
  19. }
  20. //打表
  21. void primeTable() {
  22. for (int i = 2; i < MAXN; ++i) {
  23. if (isprime(i)) {
  24. primelist[index++] = i;
  25. }
  26. }
  27. }
  28. void getprimefactors() {
  29. num = 0;
  30. for (int i = 0; i < index; ++i) {
  31. if (objNum % primelist[i] == 0) {
  32. facs[num].x = primelist[i];
  33. facs[num].cnt = 0;
  34. while (objNum % facs[num].x == 0) {
  35. facs[num].cnt++;
  36. objNum /= facs[num].x;
  37. }
  38. num++;
  39. }
  40. }
  41. if (objNum != 1) {
  42. facs[num].x = objNum;
  43. facs[num].cnt = 1;
  44. num++;
  45. }
  46. }
  47. int main() {
  48. scanf("%lld", &objNum);
  49. long long printNum = objNum;
  50. primeTable();
  51. getprimefactors();
  52. if(printNum == 1){ //需要特判处理
  53. printf("1=1");
  54. return 0;
  55. }
  56. printf("%lld=", printNum);
  57. for (int i = 0; i < num; ++i) {
  58. if(facs[i].cnt == 1){
  59. printf("%lld",facs[i].x);
  60. }
  61. else {
  62. printf("%lld^%lld", facs[i].x, facs[i].cnt);
  63. }
  64. if (i < num - 1) printf("*");
  65. }
  66. return 0;
  67. }

发表评论

表情:
评论列表 (有 0 条评论,332人围观)

还没有评论,来说两句吧...

相关阅读

    相关 因子分解

    概念:所谓质因子分解是将一个正整数n写成一个或多个质数的乘积形式。 例如:6=2\3,180=2\2\3\3\5,也可以写成指数形式,例如 180=2^2\3^2\5^1;