如何检查给定数是否为斐波那契数的Python程序

如何检查给定数是否为斐波那契数的Python程序

在本教程中,我们将学习如何检查给定的数是否为斐波那契数。

在斐波那契数列中,起始数字为: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检查给定的数字是否为斐波那契数。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程