PAT 甲级 1059 Prime Factors (25 分) ((新学)快速质因数分解,注意1=1)

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

题意:

将一个正整数分解质因数,注意坑点1=1.第一次学习质因数分解

题解:

Pollard Rho快速因数分解。时间复杂度为O(n^(1/4))。

将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
程序分析:对 n 进行分解质因数,应先找到一个最小的质数 i,然后按下述步骤完成: 
(1)如果这个质数 i 恰等于 n,则说明分解质因数的过程已经结束,打印出即可。
(2)如果n != i,但n能被 i 整除,则应打印出 i 的值,并用 n 除以 i 的商,作为新的正整数你n,
 重复执行第一步。
(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。

AC代码:

#include<iostream>
#include<queue>
typedef long long ll;
using namespace std;
ll n;
queue<ll>q;
int main(){
    cin>>n;
    ll oldN=n;
    if(n == 1) // 这一段代码非常重要 ,需要考虑n=1的情况 
    {
        cout<<n<<'='<<1;
        return 0;    
    }
    for(ll i=2;i<=n;i++){
        int num=0;
        while(n!=i)
        {
            if(n%i==0){
                n/=i;
                num++;
            }else{
                break;
            }
        }
        if(n==i){
            num++;
        }
        if(num!=0){
            q.push(i);
            q.push(num);
        }
    }
    cout<<oldN<<"=";
    int f=0;
    while(!q.empty()){
        if(f==1) cout<<"*";
        else f=1;
        ll x=q.front();q.pop();
        ll y=q.front();q.pop();
        if(y!=1) cout<<x<<"^"<<y;
        else cout<<x;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/caiyishuai/p/11558142.html