2015-03-02 218 views
0
program Primes(input,output); 
var 
    candidates, primes : Array[0..999] of Integer; 
    n, i, j : Integer; 
begin 
    for i := 0 to 999 do 
    begin 
    candidates[i] := 1; 
    end; 
    candidates[0] := 0; 
    candidates[1] := 0; 
    i := 0; 
    while i < 1000 do 
    begin 
    while (i < 1000) and (candidates[i] = 0) do 
    begin 
     i := i + 1; 
    end; 
    if i < 1000 then 
    begin 
     j := 2; 
     while i*j < 1000 do 
     begin 
     candidates[i*j] := 0; 
     j := j + 1; 
     end; 
     i := i + 1; 
    end; 
    end; 
    for i := 0 to 999 do 
    begin 
    if candidates[i] <> 0 then 
    begin 
     primes[i] := i; 
    end; 
    end; 
    for i := 0 to 999 do 
    begin 
    writeln(primes[i]); 
    end; 
    readln(); 
end. 

該代碼適用於查找素數,我需要的是隻包含素數的新數組。當打印這個時,它有零,因爲它的大小相同。任何幫助表示讚賞。謝謝。將元素添加到數組中 - Pascal

回答

0

只有在實際需要時更新primes。請您更新條目數,只有輸出的軌道,參賽人數結尾:

j := 0; 
for i := 0 to 999 do 
begin 
    if candidates[i] <> 0 then 
    begin 
    primes[j] := i; 
    Inc(j); 
    end; 
end; 

for i := 0 to j - 1 do 
    WriteLn(primes[i]); 

readln; 
0
For i:=1 to 999 do 
    Begin 
    if primes[i] <> 0 then 
     begin 
      writeln(primes[i]); 
     end; 
    end; 

如果您仍然需要幫助試試這個