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 <stdio.h>
#include <stdlib.h>
int isprime(int n)
{
    if(n == 2 || n == 3)return 1;
    if(n % 6 != 1 && n % 6 != 5)return 0;
    for(int i = 5;i * i <= n;i += 6)
    {
        if(n % i == 0 || n % (i + 2) == 0)return 0;
    }
    return 1;
}
int main()
{
    int m,n,flag = 0;
    scanf("%d",&m);
    n = m;
    printf("%d",n);
    for(int i = 2;i <= n;i ++)
    {
        if(isprime(i))
        {
            int c = 0;
            while(n % i == 0)
            {
                c ++;
                n /= i;
            }
            if(c)
            {
                if(flag)putchar('*');
                else
                {
                    flag = 1;
                    putchar('=');
                }
                printf("%d",i);
                if(c > 1)printf("^%d",c);
            }
        }
    }
    if(m == 1)
    {
        printf("=%d",n);
    }
}
原文地址:https://www.cnblogs.com/8023spz/p/8166867.html