samedi 18 septembre 2021

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.
}

Aucun commentaire:

Enregistrer un commentaire