【数学】【数论】素数的线性筛法

写在前面

  记录了个人的学习过程,同时方便复习

  • 素数的线性筛法

  有时候需要筛出来一张素数表,即1~n范围内的所有素数

  一个个枚举判断是否为素数显然太慢

  于是经过仔细的研究之后,发现如果存在正整数k(k>2)不是素数,那么它的因子里面一定包含之前的素数

  这样的话,开一个boolean数组标记一下不是素数的数,筛到它们的时候跳过就好

详见埃拉托斯特尼筛法

  但是如果这样筛,显然会有重复的筛除啊

  比如6筛去了42,7也筛去了42

  这样的情况还有很多很多,十分影响效率,时间上并不是线性的

  但如果按照一个数的最小素因子把这个数排除掉,就没问题了!

  代码如下:

C++:

 1 #include<bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 int const MAXN=100010;
 6 
 7 int prime[MAXN],tot;
 8 bool notprime[MAXN];
 9 
10 void pony_prime(int n){ 
11     notprime[0]=1;
12     notprime[1]=1;
13     for(int i=2;i<=n;++i){ 
14         if(!notprime[i])
15             prime[tot++]=i;   
16         for(int j=0; j<tot && i*prime[j]<=n;++j){ 
17             notprime[i*prime[j]]=1; 
18             if(i%prime[j]==0) break;
19         }
20      }
21 }
22 
23 int main(int argc,char *argv[],char *enc[]){
24     int m=100;
25     pony_prime(m);
26     for(int i=1;i<=m;++i){
27         if(notprime[i]) printf("%d\n",i);
28         else printf("%d    Prime\n",i);
29     }
30     return 0;
31 }

Java:

 1 class pony{
 2 
 3     static int MAXN=100010;
 4 
 5     static int[] prime=new int[MAXN];
 6     static int tot=0;
 7     static boolean[] notprime=new boolean[MAXN];
 8 
 9     static void pony_prime(int n){ 
10         notprime[0]=true;
11         notprime[1]=true;
12         for(int i=2;i<=n;++i){
13             if(!notprime[i])
14                 prime[tot++]=i;
15             for(int j=0; j<tot && i*prime[j]<=n;++j){ 
16                 notprime[i*prime[j]]=true; 
17                 if(i%prime[j]==0) break;
18             }
19          }
20     }
21 
22     public static void main(String[] args){
23         int m=100;
24         pony_prime(m);
25         for(int i=1;i<=m;++i){
26             if(notprime[i]) System.out.println(i);
27             else System.out.println(i+" Prime");
28         }
29     }
30 
31 }

猜你喜欢

转载自www.cnblogs.com/Antigonae/p/10127134.html