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).
C Program to calculate prime number in efficient way using sqrt function:
|Prime Number program in C using sqrt function|
- 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|
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).