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
题目链接
任意一个整数都一定有一个素因子,求给出数据的最大素数因子。
这个题目刚开始的时候想的有点麻烦了,看了题解之后才发现,平时的素数打表我们可以巧妙的利用一下。我们平时两层循环的素数打表不能适用于大数据打表,因为其中有些不必要的操作,我们在打表过程中,思想是以当前数作为素数,那么它的倍数肯定都不是素数,但是有一个缺点,也就是一个合数它的所有素因子都会将他遍历一遍:
for(int i = 2; i < maxn; i++)
if(!prime[i])
for(int j = i * i; j < maxn; j += i)
prime[j] = 1;
举个例子,比如说6吧,外层循环循环到2的时候,会将6操作一遍,循环到3的时候也是这样,那么这就出现了重复,但是这恰巧给我们这个题目提供了便利,因为这样的话你最后一个记录的数一定是它最大的素数因子,另外用一个数组在遍历过程中记录下当前遍历到的素数的位置就可以了。
AC代码:
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1e6 + 5;
int factor_prime[maxn], pos_prime[maxn]; //分别记录一个数的最大素因子和素数所处的位置
void init_factor_prime()
{
factor_prime[0] = factor_prime[1] = 1;
pos_prime[1] = 0;
int pos_cur = 1;
for(int i = 2; i < maxn; i++)
{
if(!factor_prime[i])
{
pos_prime[i] = pos_cur++; //记录当前素数所处的位置
for(int j = i; j < maxn; j += i)
factor_prime[j] = i; //记录j的最大素因子
}
}
return ;
}
int main()
{
init_factor_prime();
int num;
while(~scanf("%d", &num))
printf("%d\n", pos_prime[factor_prime[num]]);
return 0;
}