How to find the sum of all the primes below 10000 (ten thousand) in Pascal

1 Answer

0 votes
program PrimeSum;

uses Math; // Floor

function IsPrime(n: Integer): Boolean;
var
  i, count: Integer;
begin
  if (n < 2) or ((n mod 2 = 0) and (n <> 2)) then
    Exit(False);

  count := Floor(Sqrt(n));
  i := 3;
  while i <= count do
  begin
    if n mod i = 0 then
      Exit(False);
    i := i + 2;
  end;

  Exit(True);
end;

var
  num, i: Integer;
  sum: LongInt;

begin
  num := 10000;
  sum := 0;

  for i := 2 to num - 1 do
  begin
    if IsPrime(i) then
      sum := sum + i;
  end;

  WriteLn('sum = ', sum);
end.




(*
run:
  
sum = 5736396
  
*)

 



answered Jul 26 by avibootz
...