Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Bash program to check if the Number is a Prime or not
A prime number is a natural number greater than 1 that has exactly two factors: 1 and itself. Examples include 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, etc. In this article, we'll write a C program to check if a given number is prime or not.
Syntax
for (i = 2; i <= n/2; i++) {
if (n % i == 0) {
// Not prime
break;
}
}
Algorithm
- Step 1 − Read the number from user input
- Step 2 − Loop from 2 to n/2 to check for divisors
- Step 3 − If any divisor is found, the number is not prime
- Step 4 − If no divisors are found, the number is prime
Example 1: Basic Prime Check
This program checks if a number is prime by testing divisibility from 2 to n/2 −
#include <stdio.h>
int main() {
int n = 29, i, flag = 0;
if (n <= 1) {
printf("%d is not a prime number<br>", n);
return 0;
}
for (i = 2; i <= n / 2; i++) {
if (n % i == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d is a prime number<br>", n);
} else {
printf("%d is not a prime number<br>", n);
}
return 0;
}
29 is a prime number
Example 2: Optimized Prime Check
This optimized version checks divisibility only up to the square root of n −
#include <stdio.h>
#include <math.h>
int isPrime(int n) {
if (n <= 1) return 0;
if (n == 2) return 1;
if (n % 2 == 0) return 0;
for (int i = 3; i <= sqrt(n); i += 2) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int num = 97;
if (isPrime(num)) {
printf("%d is a prime number<br>", num);
} else {
printf("%d is not a prime number<br>", num);
}
return 0;
}
97 is a prime number
Key Points
- Numbers less than or equal to 1 are not considered prime
- The number 2 is the only even prime number
- For optimization, check divisibility only up to ?n
- Skip even divisors after checking for 2
Conclusion
Prime number checking in C can be implemented efficiently using modulo operations and loop optimization. The square root approach significantly reduces the number of iterations needed for large numbers.
Advertisements
