2019年5月14日 星期二

費波那西數列(Fibonacci)

0, 1, 1, 2, 3, 5, 8, 13 21

第0項 是0
第1項 是1
第6項 是8

https://zh.wikipedia.org/wiki/%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0%E5%88%97
數學上,費波那契數列是以遞迴的方法來定義:
  • F_{0}=0
  • F_{1}=1
  • F_{n}=F_{{n-1}}+F_{{n-2}}(n≧2)
==============================
 以python 語法來表示
 計算機概論或是資料結構開始講遞迴(recursion)時都會以 Fibonacci 來講解怎麼讓函式不斷 callback 來解出最後的答案

====最簡單法表示
def fal(i):
    if i<=1:
        return i
    else:
        ans=(fal(i-1)+fal(i-2))
        return ans
  
print(fal(6))

================

def fib(n):
    if n == 0 or n ==1:
        return n
    else:
        return fib(n-1)+fib(n-2)
print(fib(6))
===========其他

Python 斐波那契数列


nterms = int(input("你需要几项?"))

# 第一和第二项
n1 = 0
n2 = 1
count = 2

# 判断输入的值是否合法
if nterms <= 0:
   print("请输入一个正整数。")
elif nterms == 1:
   print("斐波那契数列:")
   print(n1)
else:
   print("斐波那契数列:")
   print(n1,",",n2,end=" , ")
   while count < nterms:
       nth = n1 + n2
       print(nth,end=" , ")
       # 更新值
       n1 = n2
       n2 = nth
       count += 1


=========第二款 斐波那契數列 Fibonacci Sequence
# Filename: fibonaci.py
# author by: stephen

def fib(n):        #定義一個函數叫 fib()
    if n <= 1:     #定義數列的前兩個元素為1 1
        return n
    else:
        return (fib(n-1)+fib(n-2))    #根據斐波那契數列的特性第n個元素等於前兩個元素之和

nterms = int(input("which element do you want to calculate of fibonacci?"))

if nterms <= 0:    #判斷如果用戶輸入的是負數或零就不計算
    print("please input positive number!")
else:
    print("Fibonaci is : ")
    for i in range(nterms):
        print(i, fib(i))

沒有留言:

張貼留言