杭电ACM step 2.1.4 Largest prime factor

    技术2022-07-10  115

    @TOC

    Problem Description

    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

    思路

    这道题是关于求一个数最大质因子是从2开始第几个质数的问题。 从2开始遍历所有的数。2是第一个质数,2的倍数都有2作为因子,把2的倍数都进行标记为一。3是第二个质数,同样把3的倍数都标记为二。当我们进行4的时候,发现4已经被标记了(可以筛选出素数),就进行下一个5,重复上述过程。

    代码实现

    #include <cstdio> #define max 1000001 int LPF[max]={0}; int main() { int i,n; int k=1; //k 第几个质数 for(int i=2;i<max;i++) { //LPF[i]==0,则为质数 if(!LPF[i]) { LPF[i]=k; k++; //质数的数目+1 for(int j=i*2;j<max;j+=i) //倍数关系则标记 LPF[j]=LPF[i]; } } while(scanf("%d",&n)!=EOF) { printf("%d\n",LPF[n]); } return 0; }
    Processed: 0.010, SQL: 9