傳統的方法是使用Gessel的測試。 Ñ是Fibonacci數當且僅當5N 2 + 4或5N 2 - 4是平方數。這在this SO question和this SO question中討論。你也可以找到例子here,但是這個頁面上有Python代碼(雖然很容易理解)。現在
,如果你被要求專門使用遞歸......好吧一個辦法就是這麼開始產生斐波那契數,直到生成的數字變得更或等於要測試的數量。如果匹配,測試的數字屬於斐波那契數列。如果沒有匹配,並且生成的數字大於測試的數字,則測試的數字不是斐波那契數。
這是一個基本的(和醜陋的),例如你:
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)
時間計算,如this SO question例如描述。
您需要在函數本身進行實際測試,然後您需要將其傳遞。你有適當的功能,你只需要向自己陳述你的問題,並寫下你將如何做到這一點,它會來找你。 – sean
這是功課嗎?因爲沒有任何遞歸需要更簡單的方法 – SingerOfTheFall
我知道你迭代迭代或使用數學證明更容易,但它必須遞歸地完成 – EasyQuestions