PAT-A1059 Prime Factors 题目内容及题解

Given any positive integer 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​​​​.

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 = p​1​​^k​1​​*p​2​​^k​2​​*…*p​m​​^k​m​​, where p​i​​'s are prime factors of N in increasing order, and the exponent k​i​​ is the number of p​i​​ -- hence when there is only one p​i​​, k​i​​ is 1 and must NOT be printed out.

Sample Input:

97532468

Sample Output:

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

题目大意

题目给定一个正整数,将其质因子分解并按照题目要求的形式输出。

解题思路

  1. 数据范围较大,需要使用long类型存储数据;
  2. 采用打表法记录已找到的质数可以有效减少重复计算;
  3. 将所有质因子记录后按题目要求格式输出并返回零值。

代码

#include
#include
#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;i1){
        flag=0;
        for(;i=sq){
                    Factor[fnum++]=N;
                    N=1;
                    flag=1;
                } 
            }
        }
    }
    i=0;
    while(i1){
            printf("%d^%d",F,num);
        }else{
            printf("%d",F);
        }
        if(i

运行结果

PAT-A1059 Prime Factors 题目内容及题解_第1张图片

 

解题思路2

还有一种较为简单的算法:

  1. 因为质因子需要按增序排列,因此可以借用此特点,循环操作,数出每种不同质因子的个数并进行输出;
  2. 边界条件为被除数为1,到达时跳出循环;
  3. 完成后返回零值。

代码

#include
#include
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;
}

运行结果

PAT-A1059 Prime Factors 题目内容及题解_第2张图片

 

你可能感兴趣的:(PAT甲级)