Find the given number is a prime or not in C

Find the given number is a prime or not in C

Program:


#include <stdio.h>


int main() {

    int num, i, isPrime = 1; // isPrime is a flag


    // Get input from user

    printf("Enter a number: ");

    scanf("%d", &num);


    // Check for numbers less than or equal to 1

    if (num <= 1) {

        printf("%d is not a prime number.\n", num);

        return 0;

    }


    // Check from 2 to num/2

    for (i = 2; i <= num / 2; ++i) {

        if (num % i == 0) {

            isPrime = 0; // num is divisible by something other than 1 and itself

            break;

        }

    }


    // Print result

    if (isPrime)

        printf("%d is a prime number.\n", num);

    else

        printf("%d is not a prime number.\n", num);


    return 0;

}

Output:





Comments