hdu 2136 数论+筛选质数+打表

题目来源:

http://acm.hdu.edu.cn/showproblem.php?pid=2136

Largest prime factor

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6237    Accepted Submission(s): 2206


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

 代码如下:

 1 #include<iostream>
 2 #include<stdlib.h>
 3 #include<stdio.h>
 4 #include<math.h>
 5 #include<string.h>
 6 #include<string>
 7 #include<queue>
 8 #include<algorithm>
 9 #include<map>
10 #define N 1000005
11 using namespace std;
12 int elem[N]; // 记录n 的最大质因子的位置
13 int cnt;
14 int a[N];
15 //  判断质数
16 int prime(int x)
17 {
18     if(x==0 || x==1) return 0;
19     if(x==2) return 1;
20     if(x%2==0) return 0; //剪枝,偶数都不是质数
21     for(int i=3; i*i <=x; i+=2)// 奇质数
22         if(x%i==0 ) return 0;
23     return 1;
24 }
25 // 筛选打表
26 void init()
27 {
28     elem[1]=0;
29     cnt=0;
30     for(int i=2;i<N ;i++) //质数筛选
31     {
32         if(prime(i))
33         {
34             cnt++;
35             for(int j=i;j<N ; j+=i)
36                 elem[j]=cnt;  // 记录j(j以 i 为因子) 的最大质因子的位置
37         }
38     }
39 }
40 int main()
41 {
42     init();
43     int n;
44     while(scanf("%d",&n) !=EOF)
45     {
46         printf("%d
",elem[n]);
47     }
48     return 0;
49 }
原文地址:https://www.cnblogs.com/zn505119020/p/3594489.html