向数组添加元素 - Pascal
Adding elements to an array - Pascal
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.
代码可以正常查找素数,我需要的是一个只包含素数的新数组。打印这个时,它有零,因为它的大小相同。任何帮助表示赞赏。谢谢
仅在实际需要时才更新 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;
For i:=1 to 999 do
Begin
if primes[i] <> 0 then
begin
writeln(primes[i]);
end;
end;
如果您仍然需要帮助,试试这个
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.
代码可以正常查找素数,我需要的是一个只包含素数的新数组。打印这个时,它有零,因为它的大小相同。任何帮助表示赞赏。谢谢
仅在实际需要时才更新 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;
For i:=1 to 999 do
Begin
if primes[i] <> 0 then
begin
writeln(primes[i]);
end;
end;
如果您仍然需要帮助,试试这个