Write a program which, given a positive integer n, returns 1 if n is prime and 0 otherwise.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

int is_prime(int);

int main(int argc, char **argv) {
    int number;
    printf("Enter a positive integer: ");
    scanf("%d", &number);
    if(is_prime(number))
        printf("PRIME\n");
    else
        printf("NOT PRIME\n");
    return 0;
}

int is_prime(int number) {

  if (number == 1) return 0;
    for (int i = 2; i < number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

When you compile and execute the above program it produces the following result on Linux:

Enter a positive integer: 5
PRIME

Brief Explanation

  • A prime number is a number that can be divided evenly only by 1, or itself. And it must be a whole number greater than 1.
  • The function is_prime determines if a number is prime or not. It returns 1 if prime and 0 otherwise.

Add comment


Security code
Refresh