How do I print a fibonacci sequence to the nth number in Python?

前端 未结 7 1628
忘了有多久
忘了有多久 2020-12-31 22:24

I have a homework assignment that I\'m stumped on. I\'m trying to write a program that outputs the fibonacci sequence up the nth number. Here\'s what I have so far:

7条回答
  •  遥遥无期
    2020-12-31 22:45

    This might be faster incase of long list

    # Get nth Fibonacci number 
    def nfib(nth):
      sq5 = 5**.5
      phi1 = (1+sq5)/2
      phi2 = -1 * (phi1 -1)
      resp = (phi1**(nth+1) - phi2**(nth+1))/sq5
      return long(resp)
    
    for i in range(10):
      print i+1, ": ",  nfib(i)
    

    OUTPUT

    1 :  1
    2 :  1
    3 :  2
    4 :  3
    5 :  5
    6 :  8
    7 :  13
    8 :  21
    9 :  34
    10 :  55
    

提交回复
热议问题