PAT A 1059 Prime Factors (25分)

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 

Input Specification:

Each input file contains one test case which gives a positive integer N in the range of long int.

Output Specification:

Sample Input:

97532468

Sample Output:

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

解题代码1:

#include <iostream>
using namespace std;
const int MAXN = 100000;
int prime[MAXN], k, flag, flag2;
long int n;
void init() {
    prime[0] = prime[1] = 0;
    for (int i = 2; i*i <= MAXN; i++) {
        if (prime[i]) {
            for (int j = i*i; j <= MAXN; j+=i)
                prime[j] = 0;
        }
        
    }
}
int main() {
    fill(prime, prime + MAXN, 1);
    init();
    cin >> n;
    printf("%ld=", n);
    if (n == 1)    printf("1");
    for (int i = 2; n >= 2; i++) {
        flag = k = 0;
        while (prime[i]==1 && n%i == 0) {
            k++; n /= i;
            flag = 1;
        }
        if (flag) {
            if (flag2) printf("*");
            printf("%d", i);
            flag2 = 1;
        }
        if (k >= 2) {
            printf("^%d", k);
        }
    }
    return 0;
}

备注:

如果要求一个正整数N的因子个数,只需要对其质因子分解,得到各个质因子pi的个数分别为e1、e2、...、ek,于是:

  • N的因子个数就是(e1+1)*(e2+1)*...*(ek+1)
  • N的所有因子之和为(1-p1^(e1+1)) / (1-p1) * (1-p2^(e2+1)) / (1-p2) * ... * (1-pk^(ek+1)) / (1-pk) 
原文地址:https://www.cnblogs.com/cicinnus/p/13293035.html