标签:style blog http color ar 使用 for sp strong
O(n)线性筛选n以内的素数
(1)对于任何一个素数p,都不可能表示为两个数的乘积
(2)对于任何一个合数m = p1a1p2a2…pmam,这里p1< p2 < … <pm,都能使用p1a1-1p2a2…pmam* p1进行筛选
1 fillchar(prime,sizeof(prime),1);
2 prime[1]:=false;
3 fillchar(p,sizeof(p),0);
4 total:=0;
5 for i:=2 to n do
6 begin
7 if prime[i] then begin inc(total);p[total]:=i;end;
8 for j:=1 to total do
9 begin
10 if p[j]*i>n then break;
11 prime[p[j]*i]:=false;
12 if i mod p[j]=0 then break;
13 end;
14 end;
15 for i:=1 to total do writeln(p[i]);
以下为略过偶数的线性筛选,速度还能提高一半。
标签:style blog http color ar 使用 for sp strong
原文地址:http://www.cnblogs.com/jznoi/p/4057088.html