Largest prime factor 【素筛变形】

来源:互联网 发布:c语言杨辉三角六种 编辑:程序博客网 时间:2024/05/16 06:42

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
1
2
3
4
5
Sample Output
0
1
2
1
3

一定要理解埃筛的的原理,其实就是倍数关系都被kill。 原理懂了,就会好很多 。
代码

#include<stdio.h>#include<math.h>#include<iostream>using namespace std;const int MAXN = 1e6+10;int su[MAXN]={1,1,0};int pos[MAXN]={0};void dabiao(){    int ge=1;    for(int i=2;i<MAXN;i++)        if(!su[i]){            pos[i]=ge++;//i 这个素数  在素数表中是第几个。            for(int j=i;j<MAXN;j+=i)            su[j]=i;// 这时,所有的数字都是素数i的倍数,            //不一定此时的素数i就是最大的,但是i是由小到大枚举的,            //每次都会更新,最后总会是最大的素因子        }}int main(){   int n;dabiao();   while(scanf("%d",&n)!=EOF){     printf("%d\n",pos[su[n]]);    }    return 0;}