thoga31

prime numbers

Jun 24th, 2013
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 1.40 KB | None | 0 0
  1. program prime_numbers;
  2.  
  3. type TList = array of word;
  4.  
  5. function isPrime(n : word) : Boolean;
  6. var i : word;
  7. begin
  8.     isPrime := true;
  9.     for i in [2..n div 2] do
  10.         if n mod i = 0 then begin
  11.             isPrime := false;
  12.             break;
  13.         end;
  14. end;
  15.  
  16. function listNPrimes(n : word) : TList;
  17. var i, count : word;
  18. begin
  19.     SetLength(listNPrimes, 1);
  20.     if n >= 1 then begin
  21.         count := 0;
  22.         listNPrimes[0] := 2;
  23.         i := 3;
  24.         while (count < n) do begin
  25.             if isPrime(i) then begin
  26.                 SetLength(listNPrimes, length(listNPrimes)+1);
  27.                 listNPrimes[length(listNPrimes)-1] := i;
  28.                 inc(count);
  29.             end;
  30.             inc(i);
  31.         end;
  32.     end else listNPrimes[0] := 0;
  33. end;
  34.  
  35. function listPrimesTill(n : word) : TList;
  36. var i : word = 3;
  37. begin
  38.     SetLength(listPrimesTill, 1);
  39.     if n >= 2 then begin
  40.         listPrimesTill[0] := 2;
  41.         while not(i >= n) do begin
  42.             if isPrime(i) then begin
  43.                 SetLength(listPrimesTill, length(listPrimesTill)+1);
  44.                 listPrimesTill[length(listPrimesTill)-1] := i;
  45.             end;
  46.             inc(i);
  47.         end;
  48.     end else listPrimesTill[0] := 0;
  49. end;
  50.  
  51. var elem : integer;
  52. begin
  53.     for elem in listNPrimes(10) do write(elem,', '); writeln;
  54.     for elem in listPrimesTill(40) do write(elem,', ');
  55.     readln;
  56. end.
Advertisement
Add Comment
Please, Sign In to add comment