Largest prime factor

来源:互联网 发布:java getservername 编辑:程序博客网 时间:2024/06/02 21:57
Everybody knows any number can be combined by the prime number.
Now, your task is telling me what position of the largest prime factor.
The position of prime 2 is 1, prime 3 is 2, and prime 5 is 3, etc.
Specially, LPF(1) = 0.
 
Input
Each line will contain one integer n(0 < n < 1000000).
 
Output
Output the LPF(n).
 
Sample Input
12345
 
Sample Output
01213
 


这题因为数字比较庞大,直接暴力算会超时,所以需要打表,但不是打素数表,打素数表在进行判断也会超时。需要打每个数的最大素数因子表,对于我来讲,认为技巧性挺高,当然,难了不会,会了不难。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#define maxn 1000000
using namespace std;


int visited[maxn],n;


void fact(){
    int num=0;
    for(int i=2;i<maxn;i++){//从最小素数2开始
        if(visited[i]==0) //num++;如果这个数没有被之前的素数刷新过,那么这个数就一定是素数。
        else continue;//只有是素数,才能进行刷新操作
        for(int j=i;j<maxn;j+=i){//如果是素数的倍数,那么将被刷新。
            visited[j]=num;
        }


    }
}


int main(){
    fact();
    while(scanf("%d",&n)!=EOF){
       printf("%d\n",visited[n]);
    }
    return 0;
}
0 0