首页 > 试题广场 >

Fibonacci

[编程题]Fibonacci
  • 热度指数:14154 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
    The Fibonacci Numbers{0,1,1,2,3,5,8,13,21,34,55...} are defined by the recurrence:     F0=0 F1=1 Fn=Fn-1+Fn-2,n>=2     Write a program to calculate the Fibonacci Numbers.

输入描述:
    Each case contains a number n and you are expected to calculate Fn.(0<=n<=30) 。


输出描述:
   For each case, print a number Fn on a separate line,which means the nth Fibonacci Number.
示例1

输入

1

输出

1
while True:
    try:
        n=int(input().strip())
        list1=[0,1,1]
        if n<=2:
            print(list1[n])
        else:
            while len(list1)-1!=n:
                re=list1[-1]+list1[-2]
                list1.append(re)
            print(list1[-1])
    except:
        break
发表于 2019-07-29 13:31:34 回复(0)
#最简洁实现
while True:
    try:
        num,a,b = int(input()),0,1
        for _ in range(num):
            a,b = b,a+b
        print(a)
    except Exception:
        break

编辑于 2018-10-14 12:46:06 回复(0)

python solution:

while True:
    try:
        a,res=int(input()),[0,1,1,2]
        while len(res)<a+1:
            res.append(res[-1]+res[-2])
        print(res[a])

    except:
        break
发表于 2017-10-06 15:52:55 回复(0)
def fib():
    yield 0
    yield 1
    a, b = 0, 1
    while 1:
        a, b = b, a + b
        yield b         
try:
    while 1:
        gen = fib()
        for i in xrange(input() + 1):
            current = next(gen)
        print current
except:
    pass

发表于 2016-12-26 13:16:39 回复(0)