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.
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