zoukankan      html  css  js  c++  java
  • 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 = 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

    题意:

    将一个正整数分解质因数,注意坑点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;
    }
  • 相关阅读:
    微博二级评论爬取
    爬取genome的网页和图片
    一个数据结构转换的问题
    SQLAlchemy ORM教程之二:Query
    SQLAlchemy中filter()和filter_by()有什么区别
    词云加显示条形图
    智联招聘的python岗位数据词云制作
    Python标准库——collections模块的Counter类
    MySQL5.6 windows msi安装介绍
    ICSharpCode.SharpZipLib.Zip
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/13270632.html
Copyright © 2011-2022 走看看