「学习笔记」Eratosthenes筛法

Eratosthenes筛法

概念

要得到自然数 n 以内的全部素数,必须把不大于 的所有素数的倍数剔除,剩下的就是素数。

这是一个很经典的算法,其贯穿所谓“质数数的倍数一定是合数”的理念,筛选出一定范围内的素数。

枚举数,并把当前这个数的所有的倍数记为合数,那么运行结束的时候没有被标记的数就是质数了。

两个优化:

  1. 只需考虑 n\sqrt n 以内的数的倍数
  2. 无需对合数的倍数操作

程序

program Eratothenes;
Var flag:array[1..1000005] of boolean;//flag[i]=true表示i为质数
    prime:array[1..130000] of longint;//记录质数
    n,i,j,tot:longint;
Begin
        read(n);
        fillchar(flag,sizeof(flag),1);
        tot:=0;
        flag[1]:=false;
        for i:=2 to trunc(sqrt(n)) do //优化1
        Begin
                if not flag[i] then //优化2
                Begin
                        continue;
                end;
                
                inc(tot);
                prime[tot]:=i;
                for j:=2 to n div i do
                Begin
                        flag[i*j]:=false;
                end;
        end;
end.
posted @ 2019-09-13 17:12  willbe233  阅读(95)  评论(0)    收藏  举报