我正在写一个质数查找器。从数学上讲,做起来更快,而不是做for (unsigned long i = 2; i < number/2; i++)
起来要快得多,而且仍然同样有效for (unsigned long i = 2; i < sqrt(number); i++)
但它不起作用。以下是我的代码。
// 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;
}
然后下面是我从 GCC 得到的错误。
/tmp/ccFBlUz5.o: In function `isPrime':
main.c:(.text+0xb3): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
将“数字”的类型更改为双精度会导致 % 运算符出现问题。并且为 sqrt() 调用将其转换为 double 不会改变任何内容。
有什么建议吗?
哦,我的 math.h 正在被导入,如果我注释掉那行,我会收到警告,那里有一个隐式声明。
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.
^
加上其他警告。