liuchuo/PAT

[Advanced/C++/1059] 建立素数表的操作是多余的

ZelKnow opened this issue · 0 comments

不需要建立素数表,因为

while(a%i==0) {
    count++;
    a/=i;
}

这个操作已经保证i必定为素数,若不是素数,则i必定已经遍历过它的素因子,a必定已经没有这个素因子了。所以i不会是合数。

提供一个代码,也解决了 #96 的问题:

#include<iostream>
using namespace std;
int main() {
    long long a;
    cin>>a;
    cout<<a<<"=";
    if(a==1)
        cout<<"1";
    int i;
    for(i=2;i*i<=a;i++) {
        if(i*i<0)
            break;
        int count = 0;
        while(a%i==0) {
            count++;
            a/=i;
        }
        if(count>=1) {
            if(count==1)
                cout<<i;
            else if(count > 1)
                cout<<i<<"^"<<count;
            if(a!=1)
                cout<<"*";
        }
    }
    if(a!=1)
        cout<<a;
    return 0;
}