1059 Prime Factors (25 分)

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

很简单的一个小技巧,从i=2开始向上遍历,当遇到 N % i == 0时,把N一直向下除,直到余i不等于0位置,那么我们可以得到每个N%i==0的i都会是素数,这里和欧拉函数的计算十分类似

但是特别要注意当N == 1时,要特殊判断

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <stack>
#include <queue>
#include <map>
#include <cmath>
#define INF 0x3f3f3f3f

using namespace std;
typedef long long ll;
const int maxn = 1e6;
ll n;
int prime[maxn],num[maxn];
int main()
{
    int index = 0;
    scanf("%lld",&n);
    if(n == 1)
        printf("1=1\n");
    else
    {
        ll ans = n;
        for(ll i = 2;;i ++)
        {
            if(ans == 1) break ;
            if(ans % i == 0){
                prime[index++] = i;
                while(ans % i == 0)
                {
                    ans /= i;num[index-1]++;
                }
            }
        }
        printf("%lld=",n);
        for(int i = 0;i < index;i ++)
            if(num[i] == 1)
                printf("%d%c",prime[i],i==index-1?'\n':'*');
        else
            printf("%d^%d%c",prime[i],num[i],i==index-1?'\n':'*');
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/li1615882553/article/details/84479986