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:
- isPrime Function:
bool isPrime(int num)
: This function takes an integernum
as input and returnstrue
ifnum
is a prime number, andfalse
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 returnstrue
. - For other numbers (
num > 3
), it checks divisibility from 2 up to the square root ofnum
. Ifnum
is divisible by any number in this range, it returnsfalse
. If no divisors are found, it returnstrue
.
- 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.