PAT甲 1059 Prime Factors

1059 Prime Factors (25 分)

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

代码

#include<stdio.h>
#include<math.h>
int isPrime(int n)
{
    int i,flag=1;
    if(n==0 || n==1) flag=0;
    for(i=2;i<sqrt(n);i++){
        if(n%2==0){
            flag=0;
            break;
        }
    }
    return flag;
}
int main()
{
    int n,i,j,cnt=0;
    scanf("%d",&n);
    printf("%d=",n);
    int first=0;
    if(n==1)
        printf("%d",1);
    for(i=2;i<=sqrt(n);i++){
        if(isPrime(i)){
        while(n%i==0){
            n/=i;
            cnt++;
        }
        if(cnt>1){
            if(first) printf("*");
            printf("%d^%d",i,cnt);
            first=1;}
        if(cnt==1){
            if(first) printf("*");
            printf("%d",i);
            first=1;
        }
        cnt=0;
        }
    }
    if(isPrime(n)){
        if(first) printf("*");
        printf("%d",n);
}}

猜你喜欢

转载自blog.csdn.net/qq_38290604/article/details/88523791