在本教程中,我们将学习如何检查给定的数字是否是斐波那契数。
这里,我们有一个数字“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 检查给定的数字是否是斐波那契数。