1
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.

The code works properly for finding primes, what I need is a new array that holds only the primes. When printing this one, it has zeros since it's the same size. Any help is appreciated. Thanks.

Kate
  • 45
  • 4
  • 8

2 Answers2

0

Only update primes when it's actually needed. Keep track of the number of entries you've updated, and only output that number of entries at the end:

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;
Ken White
  • 123,280
  • 14
  • 225
  • 444
0
For i:=1 to 999 do
   Begin
     if primes[i] <> 0 then
         begin
           writeln(primes[i]);
         end;
     end;

If you still need help try this

VRlad
  • 1