Prime Number program in C using sqrt (square root ) Function
In our previous blog post, we discussed What is prime number and C program to check given number is prime or not. but we used an In-efficient way, In this post, I am going to write the same program in an Efficient way. using the square root function Instead of comparing all numbers from 2 to number/2.(we used this method in the previous blog post).
Description :
C Program to calculate prime number in efficient way using sqrt function:
-
#include<stdio.h>
-
#include<math.h>
-
void main()
-
{
-
int num,i;
-
int FLAG=1;
-
printf(“Enter any Positive Number : “);
-
scanf(“%d”,&num);
-
for(i=2;i<=sqrt(num);i++)
-
{
-
if(num%i == 0)
-
{
-
FLAG = 0;
-
break;
-
}
-
}
-
if(FLAG == 1 && num > 0)
-
{
-
printf(“%d is Prime Number \n“,num);
-
}
-
else
-
{
-
printf(“%d is not a Prime Number \n“,num);
-
}
-
return;
-
}
Output :
Prime Number program in C using sqrt function |
Quick Notes:
- Here i used sqrt() function. declaration of sqrt function found in math.h so don’t forget add that header file to our program. if you forget to add that header file you will get one warning message saying
warning: incompatible implicit declaration of built-in function ‘sqrt’ [enabled by default] for(i=2;i<=sqrt(num);i++)
- This program compilation is a little different from other program compilations because we need to pass the library file name as a compilation flag. you need to pass compilation flag -lm to gcc while compiling this program otherwise you will get Linking Error. see below image for better understanding.
Possible Linking Errors and Warnings |
Explanation :
The sqrt functions in math.h have implementations in libm.so (or .a for static linking), and libm is not linked in by default. So we need to pass compilation flag -lm to gcc to link those functions also.
- Note: For a more detailed explanation of Compilation and Linking process of C Program CLICK HERE(Compilation stages in C Programming language).
in the 19th line,instead of if(FLAG == 1),it should be if(FLAG ==1&&num>1)
When I enter 4 it says thet 4 is prime.
I think it’s working fine. I just tested. please test again.
yeah man for –> num=3