Design a function to check the given number is prime or not if prime return 1 else 0 in c

26 Sep 2022 Balmiki Mandal 0 C Programming

Design a Prime Number Checker Function in C

To design a function to check if a given number is prime or not and return if prime else 0 in C, we can use the following algorithm:

  1. Take the number as input.
  2. Initialize a variable flag to 0.
  3. Iterate from to the square root of the number.
  4. If the number is divisible by any of the numbers in the loop, set flag to 1 and break the loop.
  5. If the loop completes without setting flag to 1, then the number is prime.
  6. Return flag.

C code implements this algorithm:

C Programming
int is_prime(int n) {
  int flag = 0;
  for (int i = 2; i <= sqrt(n); i++) {
    if (n % i == 0) {
      flag = 1;
      break;
    }
  }
  return flag;
}

This function can be used as follows:

C Programming
int main() {
  int n;
  printf("Enter a number: ");
  scanf("%d", &n);

  int is_prime = is_prime(n);

  if (is_prime) {
    printf("%d is a prime number.\n", n);
  } else {
    printf("%d is not a prime number.\n", n);
  }

  return 0;
}

Example output:

 

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.