zoj 2723 Semi-Prime(素筛打表+搜索优化)

Posted Reqaw’s Blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了zoj 2723 Semi-Prime(素筛打表+搜索优化)相关的知识,希望对你有一定的参考价值。

题目链接:

  http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2723

题目描述:

Prime Number Definition
An integer greater than one is called a prime number if its only positive divisors (factors) are one and itself. For instance, 2, 11, 67, 89 are prime numbers but 8, 20, 27 are not.

Semi-Prime Number Definition
An integer greater than one is called a semi-prime number if it can be decompounded to TWO prime numbers. For example, 6 is a semi-prime number but 12 is not.

Your task is just to determinate whether a given number is a semi-prime number.

Input

There are several test cases in the input. Each case contains a single integer N (2 <= N <= 1,000,000)

Output

One line with a single integer for each case. If the number is a semi-prime number, then output "Yes", otherwise "No".

Sample Input

3
4
6
12

Sample Output

No
Yes
Yes
No

 1 /*问题 判断输入的n(n的范围是2到100 0000)是否为半素数
 2 解题思路 先用素筛法建立一张[2,50 0000]的素数表放在数组里,再将素数存进向量里,然后计算出2到100 0000的半素
 3 数表放在set集合里后查表即可*/
 4 #include <cstdio>
 5 #include <set>
 6 #include <cmath>
 7 #include <vector>
 8 using namespace std;
 9 
10 int isPrim[500010];
11 
12 void prim(int n);
13 
14 int main()
15 {
16     prim(500000);
17     
18     vector<int> prim_vec;//对于未知大小的数据来说非常方便 
19     int i;
20     for(i=2;i<=500000;i++){
21         if(isPrim[i])
22             prim_vec.push_back(i);
23     }
24     
25     set<int> prim_set;//查询起来非常快速、方便 
26     int j,p;
27     for(i=0;i<prim_vec.size();i++){
28         for(j=0;j<prim_vec.size();j++){
29             if( (p = prim_vec[i]*prim_vec[j]) <=1000000)
30                 prim_set.insert(p);    
31             else
32                 break;//一种优化方法,对于有顺序的数据 
33         }
34     }
35     
36     int n;
37     set<int>::iterator it; 
38     while(scanf("%d",&n) != EOF)
39     {
40         it=prim_set.find(n);
41         if(it != prim_set.end())
42             printf("Yes\n");
43         else
44             printf("No\n");
45     }
46     return 0;    
47 } 
48 
49 void prim(int n)
50 {
51     int i,j,k;
52     
53     for(i=0;i<=n;i++)
54         isPrim[i]=1;//全部初始化为1,假定全是素数 
55     isPrim[0]=isPrim[1]=0;//0和1非素数
56      
57     k=(int)sqrt(n);
58     for(i=2;i<=k;i++){
59         if(isPrim[i]){
60             for(j=2*i;j<=n;j+=i)
61                 isPrim[j]=0;
62         }
63     }
64     /*
65     int count=0;
66     for(i=2;i<=n;i++){
67         if(isPrim[i])
68             count++;//记录50 0000以内的素数有41538个,验证素筛写的对不对 
69     }
70     printf("%d\n",count);
71     */
72 }

 

以上是关于zoj 2723 Semi-Prime(素筛打表+搜索优化)的主要内容,如果未能解决你的问题,请参考以下文章

Semi-prime H-numbers POJ - 3292 打表(算复杂度)

zoj Beautiful Number(打表)

ZOJ How Many Nines 模拟 | 打表

POj3292 Semi-prime H-numbers

POJ 3292 Semi-prime H-numbers

DFS打表Lattice Animals