Search code examples
cfor-loopif-statementprimesfunction-definition

Any idea on why this program is returning that 987 is a prime number (when it is not a prime number)?


I think the problem is with the for-loop but I cannot understand it. This is an assignment in school that I only should use for-loops and if statements to solve!

#include <stdio.h>
int is_prime(int n){
  for (int i=2;i<n;i++){
    if (n%i!=0){
      return 1;
    }
    else{
      return 0;
    };
  };
}

int main(void){
  printf("%d\n", is_prime(11));  // 11 is a prime.      Should print 1.
  printf("%d\n", is_prime(383)); // 383 is a prime.     Should print 1.
  printf("%d\n", is_prime(987)); // 987 is not a prime. Should print 0.
}


Solution

  • For starters the null statement after the if statement and the for loop itself

      for (int i=2;i<n;i++){
        if (n%i!=0){
          return 1;
        }
        else{
          return 0;
        };
        ^^^
      };
      ^^^
    

    is redundant.

    Due to the if statement the for loop is interrupted as soon as either n % i is not equal to 0 or is equal to 0. So in general the behavior of the function does not depend on whether the passed number is prime or not prime.

    If you will move the return statement

    return 1;
    

    outside the loop as others advised nevertheless the function will be still incorrect. It will show that 0 and 1 are prime numbers while they are not.

    Also the condition of the loop makes the loop inefficient at least because it is clear before entering the loop that any even number except 2 is not a prime number.

    Pay attention to that the function parameter should have unsigned integer type.

    The function can be defined the following way

    #include <stdio.h>
    
    int is_prime( unsigned long long int n )
    {
        int prime = n % 2 == 0 ? n == 2 : n != 1;
     
        for ( unsigned long long int i = 3; prime && i <= n / i; i += 2 )
        {
            prime = n % i != 0;
        }
    
        return prime;
    }
    
    int main(void) 
    {
        printf( "%d\n", is_prime( 11 ) );
        printf( "%d\n", is_prime( 383 ) );
        printf( "%d\n", is_prime( 987 ) );
      
        return 0;
    }
    

    The program output is

    1
    1
    0