Prime Number Program in C
A prime number is a natural number greater than 1 that is completely divisible only by 1 and itself. For example, 2, 3, 5, 7, 11, etc. are the first few prime numbers.
In this article, we will explore a few prime number programs in C to check whether the given number is a prime number or not.
We can check if a number is prime or not in C using two methods:
- Simple Method
- Using sqrt(N)
1. Check for Prime Number using Simple Method
In this method, we will check if any number between 2 to (N/2) can divide N completely. If such a number exists, it means that the number N is not a prime number as it is divisible by a number other than 1 and itself.
Note: We take (N/2) as the upper limit because there are no numbers between (N/2) and N that can divide N completely.
C Program to Check Prime Number Using Simple Approach
C
#include <stdio.h>
void checkPrime( int N)
{
int flag = 1;
for ( int i = 2; i <= N / 2; i++) {
if (N % i == 0) {
flag = 0;
break ;
}
}
if (flag) {
printf ( "The number %d is a Prime Number\n" , N);
}
else {
printf ( "The number %d is not a Prime Number\n" , N);
}
return ;
}
int main()
{
int N = 546;
checkPrime(N);
return 0;
|
Output
The number 546 is not a Prime Number
Time Complexity: O(n), where n is the given number.
Space Complexity: O(1)
2. Check for Prime Number using sqrt(n)
In this method, we use a mathematical property which states that,
The smallest and greater than one factor of a number cannot be more than the square root of that number.
Using this, we can reduce the numbers to be checked from (N/2) to sqrt(N) making it much more efficient than the simple method.
Algorithm
- Initialize an integer named flag with 1.
- Check the divisibility of N with every number from 1 to sqrt(N).
- If any number divides N completely, it means that N is not prime. We set the flag to 0 and stop the loop immediately.
- If we did not find any number between 2 and sqrt(N) which divides N then it means that N is prime and the flag remains 1.
C Program to Check Prime Number Using sqrt(N)
C
#include <math.h>
#include <stdio.h>
int main()
{
int N = 17;
int flag = 1;
double sqroot = sqrt (N);
for ( int i = 2; i <= sqroot; i++) {
if (N % i == 0) {
flag = 0;
break ;
}
}
if (flag) {
printf ( "%d is a prime number" , N);
}
else {
printf ( "%d is not a prime number" , N);
}
return 0;
}
|
Output
17 is a prime number
Time Complexity: O(n1/2), where n is the given number.
Auxiliary Space: O(1)
There are a few more methods to check for prime numbers which are shown in the article – Prime Numbers
Last Updated :
28 Feb, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...