1. 程式人生 > >1059 Prime Factors (25 分)

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