C Program to Check Prime Number
A Prime number is a natural number greater than 1 and divisible by 1 and itself only, for example: 2, 3, 5, 7, etc.
Method 1: Using conditional statements
In the example below, the number called MyNum is checked for prime number by dividing it with all natural numbers starting from 2 to N - 1.
#include <stdio.h> int main() { int MyNum = 17; int n = 0; for(int i = 2; i < MyNum; i++) { if(MyNum % i == 0) { n++; break; } } if (n == 0){ printf("%i is a prime number.", MyNum); } else { printf("%i is not a prime number.", MyNum); } }
The above code will give the following output:
17 is a prime number.
Method 2: Using function
In the example below, a function called primenumber() is created which takes a number as argument and checks it for prime number by dividing it with all natural numbers starting from 2 to N/2.
#include <stdio.h> static void primenumber(int); static void primenumber(int MyNum) { int n = 0; for(int i = 2; i < (MyNum/2+1); i++) { if(MyNum % i == 0) { n++; break; } } if (n == 0) { printf("%i is a prime number.", MyNum); } else { printf("%i is not a prime number.", MyNum); } } int main() { primenumber(21); }
The above code will give the following output:
21 is not a prime number.
Method 3: Optimized Code
- Instead of checking the divisibility of given number from 2 to N/2, it is checked till square root of N. For a factor larger than square root of N, there must the a smaller factor which is already checked in the range of 2 to square root of N.
- Except from 2 and 3, every prime number can be represented into 6k ± 1.
#include <stdio.h> static void primenumber(int); static void primenumber(int MyNum) { int n = 0; if (MyNum == 2 || MyNum == 3){ printf("%i is a prime number.", MyNum); } else if (MyNum % 6 == 1 || MyNum % 6 == 5) { for(int i = 2; i*i <= MyNum; i++) { if(MyNum % i == 0) { n++; break; } } if (n == 0) { printf("%i is a prime number.", MyNum); } else { printf("%i is not a prime number.", MyNum); } } else { printf("%i is not a prime number.", MyNum); } } int main() { primenumber(21); }
The above code will give the following output:
21 is not a prime number.
Recommended Pages
- C - Swap two numbers
- C Program - Fibonacci Sequence
- C Program - Insertion Sort
- C Program - Find Factorial of a Number
- C Program - Find HCF of Two Numbers
- C Program - Merge Sort
- C Program - Shell Sort
- Stack in C
- Queue in C
- C Program - Find LCM of Two Numbers
- C Program - To Check Whether a Number is Palindrome or Not
- C Program - To Check Whether a String is Palindrome or Not
- C Program - Heap Sort
- C Program - Quick Sort
- C - Swap Two Numbers without using Temporary Variable
- C Program - To Check Armstrong Number
- C Program - Counting Sort
- C Program - Radix Sort
- C Program - Find Largest Number among Three Numbers
- C Program - Print Floyd's Triangle