伝統的な方法は、ゲッセルの検定を使用することです。5N 2 + 4または5N 2 – 4が平方数である場合に限り、Nはフィボナッチ数です。これについては、この SO の質問およびこの SOの質問 で説明されています。こちらにも例がありますが、このページには Python のコードがあります (わかりやすいですが)。
さて、特に再帰を使用するように求められた場合... 1 つの方法は、生成された数値がテストしている数値とほぼ同じになるまで、フィボナッチ数の生成を開始することです。一致する場合、テストされた数値はフィボナッチ数列に属します。一致するものがなく、テストした数値よりも大きい数値を生成した場合、テストした数値はフィボナッチ数ではありません。
これはあなたのための基本的な(そして醜い)例です:
bool isFibonacci( int testedNumber, int a = 1, int b = 1 )
{
if( testedNumber == 0 || testedNumber == 1 )
return true;//returning true for 0 and 1 right away.
int nextFib = a + b;//getting the next number in the sequence
if( nextFib > testedNumber )
return false;//if we have passed the tested number, it's not in the sequence
else if( nextFib == testedNumber )
return true;//if we have a perfect match, the tested number is in the sequence
else
isFibonacci( testedNumber, b, nextFib );//otherwise, get the next fibonacci number and repeat.
}
そのまま使うisFibonacci( the_number_you_want_to_test );
O(log n)
たとえば、この SO の質問で説明されているように、フィボナッチ数は時間で計算できることに注意してください。