700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 检查给定数字是否为斐波那契数的Python程序

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

时间:2020-06-24 03:21:33

相关推荐

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

Given a number and we have to check whether it is aFibonacci number or not in Python?

给定一个数字,我们必须检查Python中是否为斐波那契数字?

检查斐波那契数 (Checking Fibonacci number)

Consider the given Fibonacci series with a first few terms:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, and so on...

考虑给定斐波那契数列的前几个术语:0、1、1、2、3、5、8、13、21、34、55、89、144,依此类推...

There is a popular formula tocheck whether a given number is a Fibonacci number or not?(5*n2 + 4) or (5*n2 – 4)

有一个流行的公式可以检查给定的数字是否为斐波那契数?(5 * n 2 + 4)或(5 * n 2 – 4)

If the result of this formula is a perfect square then the number will be a Fibonacci number.

如果此公式的结果是一个完美的平方,则该数字将是斐波那契数。

Example:

例:

Input: num = 13Output:Yes, 13 is a Fibonacci numberInput: num = 143Output:No, 144 is not a Fibonacci number

Python程序检查斐波那契数 (Python program to check Fibonacci number)

# python program to check if given# number is a Fibonacci numberimport math# function to check perferct squaredef checkPerfectSquare(n):sqrt = int(math.sqrt(n))if pow(sqrt, 2) == n:return Trueelse:return False# function to check Fibonacci numberdef isFibonacciNumber(n):res1 = 5 * n * n + 4res2 = 5 * n * n - 4if checkPerfectSquare(res1) or checkPerfectSquare(res2):return Trueelse:return False# main codenum = int(input("Enter an integer number: "))# checkingif isFibonacciNumber(num):print ("Yes,", num, "is a Fibonacci number")else:print ("No,", num, "is not a Fibonacci number")

Output

输出量

First run:Enter an integer number: 13Yes, 13 is a Fibonacci numberSecond run:Enter an integer number: 144Yes, 144 is a Fibonacci numberThird run:Enter an integer number: 143No, 143 is not a Fibonacci number

翻译自: /python/check-whether-a-given-number-is-a-fibonacci-number-or-not.aspx

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。