高效檢查第n個斐波那契數是否為10的倍數的方法?
我們將看到一種高效的方法來檢查第n個斐波那契數是否為10的倍數。假設斐波那契數列為{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987}。因此,第15個(從0開始計數)斐波那契數能被10整除。對於第16個,結果也為真。
最簡單的方法是生成直到給定項的斐波那契數,並檢查它是否能被10整除?但是這種解決方案不好,因為它不適用於較大的項。
另一種好的方法如下:
斐波那契數列:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
這些數字(以粗體字標記)能被2整除。它們的間隔是3個斐波那契數。同樣,請檢查:
斐波那契數列:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
每第5個數都能被5整除。現在3和5的最小公倍數是15。所以我們可以說,每第15個斐波那契數都能被10整除。
讓我們看看演算法來了解其思想。
演算法
fiboDivTen(term)
Begin if term is divisible by 15, then return true end if return false End
示例
#include<iostream> using namespace std; bool fiboDivTen(int term) { if(term % 15 == 0){ return true; } return false; } int main() { int term = 45; if (fiboDivTen(term)) cout << "Divisible"; else cout << "Not Divisible"; }
輸出
Divisible
廣告