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 = 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

#include
#include
#include
using namespace std;
struct number{
int p;
int k;};
struct number N[1000];
int index1=0;
int is_prime(long long  n)
{
    if (n==2)
        return 1;
    else if(n%2==0)
        return 0;
    else
    {
        long long  t=sqrt(n)+1;
        for (long long  i=2;i<=t;i++)
        {
            if (n%i==0)
                return 0;
        }
    }
    return 1;
}
void fun(long long  n)
{
    long long tt=sqrt(n)+1;
    for(long long i=2;i<=tt&&n!=0;i++)
    {
        if (is_prime(i)&&n%i==0)
        {
            N[index1].p=i;
            int kk=0;
            while(n%i==0)
            {
                kk++;
                n/=i;
            }
            N[index1++].k=kk;
        }
    }
}

int main()
{

    long long num;
    cin>>num;
    if (is_prime(num))
    {
        printf("%d=%d",num,num);
        return 0;
    }
    else
        fun(num);
    printf("%d=",num);
    if (N[0].k==1)
        printf("%d",N[0].p);
    else
        printf("%d^%d",N[0].p,N[0].k);
    for (int i=1;iif (N[i].k==1)
            printf("*%d",N[i].p);
        else
            printf("*%d^%d",N[i].p,N[i].k);
    }
    return 0;
}

你可能感兴趣的:(PAT)