打表方法解决问题

Largest prime factor

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的位置是1,3的位置是3,5的位置是3,。。。以此类推,其中1是特殊值,他的位置是0.

思路:如果一些数字有相同因数,就会被记录该因数的位置,如果这个数字没有因数,就k++,即位置++。此方法有个特殊的一点,就是该数如果有不同的质因数,起先会记录较小的质因数的位置,等到for循环,i的值到达比它大的质因数的时候会被再次记录他的位置,对之前的位置进行覆盖,直到记录它最大质因数的位置。

代码如下:

#include<iostream>
#include<cstdio>
using namespace std;

#define MAX  1000005
int a[MAX];

void calcaute(){
    int k = 1;
    for(int i = 2;i < MAX;i++){
        if(a[i]==0){
            for(int j = 1;i*j < MAX;j++){
                a[i*j] = k;//记录
            }
            k++;
        }
    }
}

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

猜你喜欢

转载自blog.csdn.net/sunshine_0880/article/details/80775110
今日推荐