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 In-efficient way, In this post I am going to write the same program in Efficient way. using square root function Instead of comparing all numbers from 2 to number/2.(we used this method in 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 little different to other programs compilations because we need to pass library file name as 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 more detailed explanation of Compilation and Linking process of C Program CLICK HERE(Compilation stages in C Programming language).