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在素数表中的位置为1,3为2,5的位置是3……依此类推(1的位置为0)。
题目说任何数都能由素数相乘得到。
素数的倍数肯定不是素数,这点可以明确,如2是素数,则4,6,8是合数。则4的最大质因数(2)在素数表中的位置为1,6的最大质因数为3,所以只需知道3在素数表中的位置即可。因为每个数都能由素数相乘得到,于是乎可以这样假设,2是所有2的倍数的整数的最大质因数,则所有以2为倍数的整数的最大质因数在素数表中的位置为1,姑且先这么认为,然后再以3为步长,再以5为步长,于是像6,15的最大质因子在素数表中的位置分别调整为2和3了。按照这个思路算法如下:
#include<stdio.h>
int prim[1000000];
int main(){//cnt为跟踪素数表的位置
int n,cnt = 1,i,j;
for(i = 2;i < 1000000;i++){
if(prim[i])//值非0,为合数,不是我们的目标
continue;
for(j = i;j < 1000000;j += i)
prim[j] = cnt;
cnt++;
}
while(scanf("%d",&n) != EOF)
printf("%d\n",prim[n]);
return 0;
}
讲的有点罗嗦了,其实想通了,也很简单。