编写一些代码:在Python中找到斐波那契数列

编写一些代码在Python中找到斐波那契数列,具体代码示例如下:

# Define a function to find the nth Fibonacci number
def fibonacci(n):
  # Base cases: 0 and 1
  if n == 0:
    return 0
  elif n == 1:
    return 1
  # Recursive case: use the formula F(n) = F(n-1) + F(n-2)
  else:
    return fibonacci(n-1) + fibonacci(n-2)

# Ask the user for a positive integer
n = int(input("Enter a positive integer: "))

# Print the Fibonacci sequence up to the nth term
print("The Fibonacci sequence up to the", n, "th term is:")
for i in range(n):
  print(fibonacci(i), end=" ")

编写一些代码:在Python中找到斐波那契数列

拓展知识:

在数学中,斐波那契数,通常表示为Fₙ,形成一个序列,即斐波那契数列,其中每个数字都是前面两个数字之和。斐波那契数最早在印度数学中被描述,早在公元前200年,Pingala在工作中列举了由两个长度的音节组成的梵文诗歌的可能模式。它们是以意大利数学家比萨的莱昂纳多命名的,莱昂纳多后来被称为斐波纳契,他在1202年的《Liber Abaci》一书中把这个序列引入了西欧数学。

编写一些代码:在Python中找到斐波那契数列

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注