在本教程中,我們將學習如何檢查給定的數字是否是斐波那契數。
這裡,我們有一個數字「n」,我們必須檢查它是否是斐波那契數。斐波那契數列的起始數有:0、1、1、2、3、5、8、13、21、34、55、89、144 等等。
示例:
Input number: 5
Output: Yes, the given number is a Fibonacci_Number.
Input number: 22
Output: No, the given number is not a Fibonacci_Number.
Input number: 55
Output: Yes, the given number is a Fibonacci_Number.
我們還可以使用斐波那契數的以下屬性來檢查給定的數是否是斐波那契數:
- 只有當(5 R R + 4)或(5 R R – 4)中的一個或兩個都是完美平方時,一個數才是斐波那契數。
Python 程序:檢查給定數字是否為斐波那契數:
import math as m
# Here, we will create a utility function that will return true if K is a perfect square
def is_Perfect_Square(K):
s = int(m.sqrt(K))
return s * s == K
# Now, we will create a function which will return "true" if R is a Fibinacci Number,
# else it will return "false"
def is_Fibonacci(R):
# R is a Fibinacci number only if one of (5 * R * R + 4) or (5 * R * R - 4) or both
# of them are perferct square
return is_Perfect_Square(5 * R * R + 4) or is_Perfect_Square(5 * R * R - 4)
# Now, we will create a utility function for testing the above functions
for J in range(1, 22):
if (is_Fibonacci(J) == True):
print ("Number:", J, ": Yes, the given number is a Fibonacci_Number")
else:
print ("Number:", J, ": No, the given number is not a Fibonacci_Number")
輸出:
Number: 1 : Yes, the given number is a Fibonacci_Number
Number: 2 : Yes, the given number is a Fibonacci_Number
Number: 3 : Yes, the given number is a Fibonacci_Number
Number: 4 : No, the given number is not a Fibonacci_Number
Number: 5 : Yes, the given number is a Fibonacci_Number
Number: 6 : No, the given number is not a Fibonacci_Number
Number: 7 : No, the given number is not a Fibonacci_Number
Number: 8 : Yes, the given number is a Fibonacci_Number
Number: 9 : No, the given number is not a Fibonacci_Number
Number: 10 : No, the given number is not a Fibonacci_Number
Number: 11 : No, the given number is not a Fibonacci_Number
Number: 12 : No, the given number is not a Fibonacci_Number
Number: 13 : Yes, the given number is a Fibonacci_Number
Number: 14 : No, the given number is not a Fibonacci_Number
Number: 15 : No, the given number is not a Fibonacci_Number
Number: 16 : No, the given number is not a Fibonacci_Number
Number: 17 : No, the given number is not a Fibonacci_Number
Number: 18 : No, the given number is not a Fibonacci_Number
Number: 19 : No, the given number is not a Fibonacci_Number
Number: 20 : No, the given number is not a Fibonacci_Number
Number: 21 : Yes, the given number is a Fibonacci_Number
結論
在本教程中,我們討論了用戶如何使用 Python 檢查給定的數字是否是斐波那契數。
原創文章,作者:S1VUH,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/130906.html