I'm writing a prime number finder. Mathematically, it is faster to, instead of doing for (unsigned long i = 2; i < number/2; i++)
it's a lot faster, and still just as effective, to do for (unsigned long i = 2; i < sqrt(number); i++)
But it's not working. The below is my code.
// Stuff goes up here, including a function prototype and:
#include <math.h>
char isPrime (unsigned long number)
{
if (number <= 1) {
return 0;
}
long double sqrtOfNumber = sqrt(number); // Calculate once.
for (unsigned long i = 2; i < sqrtOfNumber; i++) {
if (number%i == 0) { // It has a divisor.
return 0;
}
}
// Nothing broke us yet....
return 1;
}
And then below is the error I get from GCC.
/tmp/ccFBlUz5.o: In function `isPrime':
main.c:(.text+0xb3): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
Changing the type of "number" to a double causes problems with the % operator. And casting it to a double for the sqrt() call doesn't change anything.
Any advice?
Oh, and my math.h IS being imported, if I comment out that line, I get warned that there is an implicit declaration there.
main.c: In function 'isPrime':
main.c:28:2: warning: implicit declaration of function 'sqrt' [-Wimplicit-function-declaration]
long double sqrtOfNumber = sqrt(number); // Calculate once.
^
main.c:28:29: warning: incompatible implicit declaration of built-in function 'sqrt' [enabled by default]
long double sqrtOfNumber = sqrt(number); // Calculate once.
^
plus the other warning under that.
-lm
needs to added to the command line after the file that requires that library for example if main.c
required the math library then you would use:
gcc -x c main.c -lm
You can see a live example here, there are three command lines available in the example. One without -lm
, one with -lm
before the file that needs it one after the files that needs it.
For completeness sake if we refer to the gcc docs on options for Linking it says the following for -l
:
[...]It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, ‘foo.o -lz bar.o’ searches library ‘z’ after file foo.o but before bar.o. If bar.o refers to functions in ‘z’, those functions may not be loaded. [...]
You need to link the math library. Use the -lm
option on the command line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With