试题 算法提高 分解质因数

卡点:

如果这个数是一个很大的质数就会超时,因此需要判断,如果直接遍历,会卡40%的样例。

代码:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
typedef long long ll;
const int maxn = 100;
bool judge(ll n){
    for(int i=2;i<=sqrt(n);i++){
        if(n%i==0)
            return false;
    }
    return true;
}
int main(){
    ll n;
    cin>>n;
    ll m = n;
    for(int i=2;i<=n;i++){
        while(n%i==0){
            cout<<i<<" ";
            n = n/i;
        }
        if(judge(n)&&n!=1){
            cout<<n<<endl;
            break; 
        }
    }
    cout<<endl;
    return 0;
} 
原文地址:https://www.cnblogs.com/lusiqi/p/13806467.html