Adrian
Adrian

Reputation: 17

Max prime number in an array

My task is to find the max prime number in an array. My code does not work for numbers with more than one digit. The function only returns the first digit in that case. I guess I have some problem with pointer?

#include <stdio.h>

int maxprime(int* array, int size)
{
  int max=0,i,j,a,counter=0;
  for(i=0;i<size;i++){
    a=array[i];
    for(j=2;j<a;j++){
      if(a%j==0) break;
      counter++;
    }
    if(counter==a-2) {
      if(a>max)
    max=a;
    }
  }
  return max;
}

int main()
{
  int array[10] = {225, 224, 223, 226};                                                             
  printf("%d", maxprime(array, 4));
}

Upvotes: 0

Views: 1757

Answers (1)

Jacob Faib
Jacob Faib

Reputation: 1130

As pointed out by the other response, your counter variable is pointless. All you need to do is check that you exited your innermost loop via the break:

#include <stdbool.h>

int maxprime(int* array, int size)
{
  int max=0;
  for(int i=0;i<size;i++){
    /* assume every number is prime */
    bool prime=true;
    int a=array[i];
    for(int j=2;j<a;j++){
      if(a%j==0) {
        /* was divisible, so not prime after all */
        prime=false;
        break;
      }
    }
    /* only update max if you found a prime */
    if (prime) max=a>max?a:max;
  }                                                                                                 
  return max;
}

Upvotes: 1

Related Questions