题目描述
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.
输入描述
Each input file contains one test case which gives a positive integer N in the range of long int.
输出描述
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.
输入例子
97532468
输出例子
97532468=2^211171011291
解题思路
其实这是一道相对简单的素数因子求解问题。思路是对n进行素因子分解,用的素数x最大到小于sqrt(n)的最大素数xMax。在分解的同时,随着x不断增大,n不断减小,即n/=x。
当x取到xMax时,有两种情况,第一种,此时,n等于1,第二种n>1。
第一种情况,即已经分解完毕。
解释一下第二种情况,n>1,也就是对n进行分解,他的质因数除了分布在2~xMax之间,还有因子分布在(xMax,n]之间,那么这个因子是合数还是质数呢?答案是,一定是质数。为什么呢?
- 假如n本身是质数,那么这个因子就是它本身
- 假如n是合数,经过前面的分解,此时的n,写作n’,它包含的因子中一定不存在小于xMax的素因子,那么它会不会存在介于(xMax,n’)的质因子呢?假如存在,那么必定还存在一个小于xMax的质因子,矛盾,因此,n’一定不存在小于n’的质因子,即它本身就是它的质因子。
以下是代码
#include <iostream>
#include<cmath>
using namespace std;
int main(void) {
long long n;
while(cin>>n) {
cout << n << "=";
if(n==1) {
cout << 1 << endl;
continue;
}
bool first = true;
int count;
for (int i = 2; i <= (int) sqrt(n); i++) {
count = 0;
while (n % i == 0) {
count++;
n /= i;
}
if (count) {
if (first)
first = false;
else {
cout << "*";
}
count == 1 ? cout << i : cout << i << "^" << count;
}
}
if (n == 1)
cout << endl;
else {
if(!first)
cout<<"*";
cout << n << endl;
}
}
return 0;
}