Prime Number Checker in C

 

 

Check if a Number is Prime

This program checks if a given number is prime.

Program in C:


#include <stdio.h>
#include <stdbool.h>

// Function to check if a number is prime
bool isPrime(int num) {
    // Handling special cases
    if (num <= 1) {
        return false;
    }
    if (num <= 3) {
        return true;
    }

    // Check for divisibility from 2 to sqrt(num)
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    
    return true;
}

int main() {
    int number;
    
    // Input number from user
    printf("Enter a number: ");
    scanf("%d", &number);
    
    // Check if the number is prime
    bool prime = isPrime(number);
    
    // Print the result
    if (prime) {
        printf("%d is a prime number.\n", number);
    } else {
        printf("%d is not a prime number.\n", number);
    }

    return 0;
}
        

Output:

Enter a number: 7
7 is a prime number.

 

Explanation:

  1. isPrime Function:
    • bool isPrime(int num): This function takes an integer num as input and returns true if num is a prime number, and false otherwise.
    • It first handles special cases where numbers less than or equal to 1 are not prime (return false).
    • For numbers 2 and 3 (num <= 3), it directly returns true.
    • For other numbers (num > 3), it checks divisibility from 2 up to the square root of num. If num is divisible by any number in this range, it returns false. If no divisors are found, it returns true.
  2. Main Function:
    • int main(): This is the main function where the program starts execution.
    • It prompts the user to enter a number and reads the input using scanf.
    • It calls the isPrime function to check if the entered number is prime.
    • Based on the return value of isPrime, it prints whether the number is prime or not.

One Reply to “Prime Number Checker in C”

  1. With thanks, I appreciate it.
    casino en ligne fiable
    Superb data Thanks a lot!
    meilleur casino en ligne
    Thanks a lot, Quite a lot of forum posts.
    casino en ligne
    Many thanks, Very good information!
    casino en ligne
    Cheers! I like it!
    meilleur casino en ligne
    You said this wonderfully!
    casino en ligne fiable
    Thanks. Good information!
    casino en ligne fiable
    You’ve made your point quite nicely!.
    casino en ligne
    You’ve made your point very clearly!.
    casino en ligne francais
    Incredible a lot of beneficial data!
    casino en ligne

Leave a Reply to casino en ligne fiable Cancel reply

Your email address will not be published. Required fields are marked *