Given any positive integer
N
N
N, you are supposed to find all of its prime factors, and write them in the format
N
=
p
1
k
1
×
p
2
k
2
×
⋯
×
p
m
k
m
N = p_1^{k_1} × p_2^{k_2} ×⋯×p_m^{k_m}
N=p1k1×p2k2×⋯×pmkm
Input Specification:
Each input file contains one test case which gives a positive integer N N N in the range of long int.
Output Specification:
Factor
N
N
N in the format
N
N
N =
p
1
p_1
p1 ^
k
1
k_1
k1 *
p
2
p_2
p2 ^
k
2
k_2
k2 *
… *
p
m
p_m
pm ^
k
m
k_m
km, where
p
i
p_i
pi's are prime factors of
N
N
N in increasing order,and the exponent
k
i
k_i
ki is the number of
p
i
p_i
pi,
−
−
--
−− hence when there is only one
p
i
p_i
pi,
k
i
k_i
ki is
1
1
1 and must NOT be printed out.
Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
Method:
素数表:数字
n
n
n 不可以被大于
n
\sqrt{n}
n 整除,而
n
n
n 的范围是 long int
,使用 LONG_MAX
时数组开的过大,所以素数表开到 sqrt(INT_MAX)
即可。
Solution:
#include <iostream>
#include <vector>
#include <cmath>
#include <climits>
using namespace std;
bool IsPrime(int);
const int maxn = int(sqrt(INT_MAX * 1.0));
int prime[maxn];
struct factor{
int p, k;
};
vector<factor> fac;
int main() {
int cnt = 0;
for (int i = 0; i <= maxn; i++)
if (IsPrime(i)) prime[cnt++] = i;
int n = 0;
cin >> n;
cout << n << "=";
if (n == 1) {
cout << "1" << endl;
return 0;
}
factor temp;
for (int i = 0; i <= cnt && prime[i] <= n; i++) {
int num = 0;
while (n % prime[i] == 0) {
n /= prime[i];
num++;
}
if (num > 0) {
temp.p = prime[i]; temp.k = num;
fac.push_back(temp);
}
}
for (int i = 0; i < fac.size(); i++) {
cout << fac[i].p;
if (fac[i].k> 1) cout << "^" << fac[i].k;
if (i != fac.size()-1) cout << "*";
}
return 0;
}
bool IsPrime(int n) {
if (n < 2) return false;
int limit = int(sqrt(n * 1.0));
for (int i = 2; i <= limit; i++)
if (n % i == 0) return false;
return true;
}