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:97532468Sample Output:
97532468=2^2*11*17*101*1291
这道题的大意是输入一个数,把他进行质因子分解并按格式输出。
为了方便解题,首先我们得了解一些数学知识:
1.对于正整数N,如果存在不同于1和它自身的因数,那么因数要么等于sqrt(N)(N的平方根),要么在sqrt(N)的左右成对出现。
2.对于正整数N,把它因式分解,要么所有的质因子都小于等于sqrt(N),要么只存在一个质因子大于sqrt(N),其余质因子全小于sqrt(N)。
所以我们可以让i从2-sqrt(N)开始枚举,如果N能整除,那么把该因子记录下来,同时该因子的数目+1,N=N/i。
如果过程结束后N不等于1,那么现在的N就是唯一一个大于sqrt(N)的质因子,也记录下来,令他的数目为1.
注意1是特殊情况,要特殊处理。
源代码如下:
#include<cstdio>
#include<cmath>
struct factor {
int x;//质因子
int cnt;//该质因子的个数
}fac[10];
long long N;
int factorNum = 0;//表示第几个质因数,如2可能是第一个质因数,3可能是第二个质因数
//求出数N的所有质因子,并保存在结构体fac中
void getFactor(long long num) {
if (num == 1) {
fac[0].x = 1;
return;
}
double sqr = sqrt(num);
for (long long i = 2; i <= sqr; ++i) {
if (num%i == 0) {
fac[factorNum].x = i;
fac[factorNum].cnt = 0;
while (num%i == 0) {
fac[factorNum].cnt++;
num /= i;
}
factorNum++;
}
}
if (num != 1) {
fac[factorNum].x = num;
fac[factorNum].cnt = 1;
}
}
int main(){
scanf("%lld", &N);
getFactor(N);
//输出结果
printf("%lld=", N);
if (factorNum == 0) {
printf("%d", fac[0].x);
}
else {
for (int i = 0; i < factorNum; ++i) {
printf("%d", fac[i].x);
if (fac[i].cnt != 1) printf("^%d", fac[i].cnt);
if (i != factorNum - 1) printf("*");
}
}
return 0;
}