主题:[求助]tju1008,加分!!
贺天行宝
[专家分:2300] 发布于 2006-04-29 20:31:00
要做素数表1到1000000,我试了几种方法,时间都不行,谁能把程序发上来给我看看?谢谢!
1:
const maxn=1000000;
var
s:array[1..maxn]of boolean;
i,j,k,l,m,n:longint;
begin
fillchar(s,sizeof(s),false);
s[1]:=true;i:=2;
while true do
begin
while (i<=maxn)and(s[i]=true) do inc(i);
if i=maxn+1 then break;
k:=i;l:=i;
while k<=maxn do begin s[i]:=true; k:=k+l; end;
end;
end.
2:
var
s:array[1..1000000]of longint;
i,j,k,l,m,n:longint;
flag:boolean;
begin
s[1]:=1;s[2]:=2;n:=2;
for k:=3 to 1000000 do
begin
m:=trunc(sqrt(k))+1;
i:=2;flag:=true;
while (i<=n)and(s[i]<=m) do
begin
if k mod s[i]=0 then begin flag:=false; break; end;
inc(i);
end;
if flag then begin inc(n); s[n]:=k; end;
end;
end.
都不行,谁帮帮我!
回复列表 (共6个回复)
沙发
1234563 [专家分:10] 发布于 2006-05-13 14:43:00
var
m,n,i,j,k,x:longint;
b:boolean;
a:array[1..168]of integer;
procedure rgt;
begin
a[1]:=2;
k:=1;
for i:=3 to 1000 do
begin
b:=true;
for j:=2 to trunc(sqrt(i)) do
if i mod j=0 then
begin
b:=false;
break;
end;
if b then begin
inc(k);
a[k]:=i;
end;
end;
end;
begin
rgt;
while not seekeof do
begin
readln(m,n);
x:=0;
if m=1 then inc(m);
for i:=m to n do
begin
b:=true;
for j:=1 to 168 do
if (i mod a[j]=0)and(i<>a[j])
then begin b:=false; break;end;
if b then inc(x);
end;
writeln(x);
end;
end.
板凳
maxumi [专家分:2200] 发布于 2006-05-16 10:32:00
是tju1010吧?
program tju1010;
const
max=999999;
bitmask:array[0..7]of byte=(127,191,223,239,247,251,253,254);
rightmask:array[0..8]of byte=(255,127,63,31,15,7,3,1,0);
var
bits:array[0..255]of byte;
prime:array[0..max shr 3]of word;
count:array[0..max shr 3]of longint;
m,n,q1,q2,r1,r2:longint;
procedure calbits;
var
i,j,x:byte;
begin
for i:=0 to 255 do begin
x:=i;
for j:=1 to 8 do begin
if odd(x) then inc(bits[i]);
x:=x shr 1;
end;
end;
end;
procedure delprime(x:longint);
var
q,r:longint;
begin
q:=x shr 3;r:=x and 7;
if prime[q] and bitmask[r]<prime[q] then dec(count[q]);
prime[q]:=prime[q] and bitmask[r];
end;
procedure calprime;
var
i,j:longint;
begin
fillchar(prime,sizeof(prime),255);
for i:=0 to max shr 3 do count[i]:=8;
delprime(0);delprime(1);
for i:=2 to trunc(sqrt(max)) do begin
j:=i shl 1;
while j<=max do begin
delprime(j);
inc(j,i);
end;
end;
for i:=1 to max shr 3 do inc(count[i],count[i-1]);
end;
begin
calbits;
calprime;
repeat
read(m,n);
q1:=m shr 3;r1:=m and 7;q2:=n shr 3;r2:=n and 7;
writeln(count[q2]-count[q1]+bits[prime[q1] and rightmask[r1]]-bits[prime[q2] and rightmask[r2+1]]);
until seekeof;
end.
3 楼
济公二世 [专家分:200] 发布于 2006-08-18 22:14:00
我也是呀!!大家有更省时间的方法写下来吧!我做的素数表也是超时的!悲哀呀!
4 楼
interegg [专家分:80] 发布于 2006-08-25 10:08:00
小弟不才,不能用筛法吗?
5 楼
popoa [专家分:100] 发布于 2006-10-06 22:01:00
时间是多少?
6 楼
游侠UFO [专家分:1200] 发布于 2006-10-07 12:19:00
[quote]小弟不才,不能用筛法吗?
[/quote]
筛法空间又超,我们老师讲用分段筛.一段一段的筛...但具体怎么实现我还没实验过.
我来回复