Prime numbers are the numbers greater than 1 which are divisible only by 1 and itself, like 3 is divisible by 1 and 3 only. So, if a natural number n is a prime number, then it is divisible by only 1 and n and not divisible by any number from the sequence 2, 3, 4, ….. , (n - 1).
To check whether a number (n) is prime or not, check whether number n is multiple of any integer between 2 and √n. If there exist such a number then n is not a prime number, otherwise n is a prime number.
Algorithm:
- Let the number to checked is
nandibe any temporary number. - Set
i= 2. - Check whether
iis less than or equal to square root ofn. - If no, then
nis a prime number, otherwise move to step 5. - Check whether number
nis multiple of numberi. - If yes, number
nis not a prime number, otherwise move to step 7. - Increment the value of
iby 1 and move to step 3.
Instructions:
- You need following two header files for this program to work.
#include <stdio.h> #include <math.h>
- Now ask the user to enter a number which he/she wants to check.
int num, temp; printf("Enter the number you want to check : "); scanf("%d", &num); - Now if the input number is 1, it is not prime number else call function
isPrime(function to check primality of a number) and if the function returns 1, the number is prime else number is not prime.
int isPrime(int); if(num == 1) temp = 0; else temp = isPrime(num); if(temp == 1) printf("%d is a prime number", num); else printf("%d is not a prime number", num); - In function
isPrimeusing an integeri(initially set to 2) in a while loop, check whether the numberidivides perfectly the number input by user or not and return 0 if it divides otherwise increment the value ofiand keep on checking untill the value of i becomes larger than square root of input number. So, if no number from 2 to √n divides perfectly the input number, then the number is prime.
int isPrime(int num) { int i = 2; while(i <= sqrt(num)) { if(num % i == 0) return 0; else i++; } return 1; }
Here are some screenshots of the working of sample program.
You can download the sample code from here.



