我想問應該用哪一種方法較快阿?
因為我用愛氏去找出所有質數(3,20000000)
之後就找出第N對twins primes
但用愛氏就會TLE(3s),之後我就想爆出100000對twins prime,但那個文字檔有3MB多,結果我放棄了
那麼請問有什麼好的方法嗎?
以下是我的程式碼
program twin_prime; const max=20000000; var prime:array[3..max] of boolean; n,i,j,count:longint; procedure find_prime; //all prime[i] are true first var temp:longint; begin i:=3; while i<=max do begin if prime[i] then begin temp:=max div i; j:=3; while j<=temp do begin prime[i*j]:=false; j:=j+2; end; end; i:=i+2; end; end; begin for i:= 3 to max do prime[i]:=true; find_prime; while not eof do begin readln(n); count:=0; i:=3; while i<=max-2 do begin if ((prime[i]) and (prime[i+2])) then inc(count); if count=n then break; i:=i+2; end; writeln('(',i,' ',i+2,')'); end;
end.
請賜教
program twin_prime;
const max=20000000;
var prime:array[3..max] of boolean;
n,i,j,count:longint;
procedure find_prime; //all prime[i] are true first
var temp:longint;
begin
i:=3;
while i<=max do
begin
if prime[i] then
begin
temp:=max div i;
j:=3;
while j<=temp do
begin
prime[i*j]:=false;
j:=j+2;
end;
end;
i:=i+2;
end;
end;
begin
for i:= 3 to max do
prime[i]:=true;
find_prime;
while not eof do
begin
readln(n);
count:=0;
i:=3;
while i<=max-2 do
begin
if ((prime[i]) and (prime[i+2])) then inc(count);
if count=n then break;
i:=i+2;
end;
writeln('(',i,' ',i+2,')');
end;
end.
程式碼輸出終於弄好-.-