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:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
题目大意
题目给定一个正整数,将其质因子分解并按照题目要求的形式输出。
解题思路
- 数据范围较大,需要使用long类型存储数据;
- 采用打表法记录已找到的质数可以有效减少重复计算;
- 将所有质因子记录后按题目要求格式输出并返回零值。
代码
#include<stdio.h>
#include<math.h>
#define maxn 1000010
#define int long
int Prime[maxn]={2,3},pnum=2;
int Factor[maxn],fnum=0;
int isPrime(int x){
int sq,i;
if(x==1){
return 0;
}
if(x==2||x==3){
return 1;
}
sq=(int)sqrt(1.0*x);
for(i=0;i<pnum&&Prime[i]<=sq;i++){
if(x%Prime[i]==0){
return 0;
}
}
Prime[pnum++]=x;
return 1;
}
int main(){
int N,i=0,flag,num;
int F,sq;
scanf("%d",&N);
printf("%d=",N);
if(N==1){
printf("1\n");
return 0;
}
while(N>1){
flag=0;
for(;i<pnum;){
if(N%Prime[i]==0){
Factor[fnum++]=Prime[i];
N/=Prime[i];
flag=1;
break;
}else{
i++;
}
}
if(flag){
continue;
}else{
sq=(int)sqrt(1.0*N);
while(flag==0){
//找下一个质数
for(num=Prime[pnum-1]+1;;num++){
if(isPrime(num)){
break;
}
}
if(N%Prime[i]==0){
Factor[fnum++]=Prime[i];
N/=Prime[i];
flag=1;
break;
}else{
i++;
}
if(Prime[i-1]>=sq){
Factor[fnum++]=N;
N=1;
flag=1;
}
}
}
}
i=0;
while(i<fnum){
F=Factor[i++];
num=1;
while(i<fnum&&Factor[i]==F){
i++;
num++;
}
if(num>1){
printf("%d^%d",F,num);
}else{
printf("%d",F);
}
if(i<fnum){
printf("*");
}else{
printf("\n");
}
}
return 0;
}
运行结果
解题思路2
还有一种较为简单的算法:
- 因为质因子需要按增序排列,因此可以借用此特点,循环操作,数出每种不同质因子的个数并进行输出;
- 边界条件为被除数为1,到达时跳出循环;
- 完成后返回零值。
代码
#include<stdio.h>
#include<math.h>
int isPrime(int x)
{
if(x<=1){
return 0;
}
int i,sqr=sqrt(1.0*x);
for(i=2;i<=sqr;++i){
if(x%i==0){
return 0;
}
}
return 1;
}
int main(){
int i,j,n;
scanf("%d",&n);
printf("%d=",n);
if(n==1){
printf("1\n");
}else{
for(i=2;1;++i){
j=0;
if(isPrime(i)){
for(;n%i==0;){
n/=i;
++j;
}
}
if(j>1){
printf("%d^%d",i,j);
}else if(j==1){
printf("%d",i);
}if(n>1&&j>0){
printf("*");
}if(n==1){
break;
}
}
}
return 0;
}
运行结果