Count prime numbers from an array in Pascal

1.8k views Asked by At

I have a problem in PAscal. I want to count prime numbers but no result : My code is:

Program arrayToFunction;
const
 size = 5;
type
  a = array [1..size] of integer;
var
 aNumbers:  a = (1, 7, 3, 4, 5);
 iCountNumbers: integer;
function countPrimeNumbers( var arr: a) : integer;
  var
   i :0..size;
   sum,j,count: integer;
  begin
  sum := 0;count:=0;
  for i := 0 to size do
  begin
      for j := 2 to arr[i] do
          begin
               if(arr[i] mod j = 0) then sum:=1;
          end;
      if(sum=0) then count:=count+1;

  end;
 countPrimeNumbers := count;
end;
begin
 iCountNumbers := countPrimeNumbers( aNumbers ) ;*)
  writeln( 'Numbers: ', iCountNumbers);
  readln;
end.  

For this array I want to get 3 but I get 2...I don't understand where is my problem. Help me please

1

There are 1 answers

3
ganbustein On

You have type a = array [1..size] of integer;, but then you iterate over the array using for i := 0 to size. The subscript needs to match the declared range.

You set sum := 0; before entering that loop, but never set it back to zero again. Once you find a non-prime, you'll set sum := 1;, and there it will stay. You never detect a prime once you've detected a non-prime.

The two primes you found were whatever garbage is at arr[0], and the 1 at arr[1]. Notice that 1 is not a prime, but your code will conclude it is. 7 is a prime, but your code will think it is not, because it will eventually notice that it's divisible by itself.