5

私は素数ファインダーを書いています。数学的には、実行する代わりに、実行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

「数値」のタイプを double に変更すると、% 演算子で問題が発生します。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.
                         ^

さらに、その下にある他の警告。

4

2 に答える 2

1

数学ライブラリをリンクする必要があります。-lmコマンドラインでオプションを使用します。

于 2013-10-15T02:15:36.127 に答える