フィボナッチ数列を出力するPythonプログラム

Python

フィボナッチ数列は、0、1、1、2、3、5、8 …の整数列です。

最初の2つの項は0と1です。他のすべての項は、前の2つの項を加算することによって取得されます。 これは、n番目の項が(n-1)番目と(n-2)番目の項の合計であると言うことを意味します。

ソースコード

# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms
n1, n2 = 0, 1
count = 0

# check if the number of terms is valid
if nterms <= 0:
   print("Please enter a positive integer")
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
else:
   print("Fibonacci sequence:")
   while count < nterms:
       print(n1)
       nth = n1 + n2
       # update values
       n1 = n2
       n2 = nth
       count += 1

出力

How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8

ここでは、用語の数をに格納します nterms。 最初の項を0に初期化し、2番目の項を1に初期化します。

用語の数が2を超える場合は、 while 前の2つの用語を追加して、シーケンス内の次の用語を見つけるためにループします。 次に、変数を交換(更新)して、プロセスを続行します。

再帰を使用してこの問題を解決することもできます。再帰を使用してフィボナッチ数列を出力するPythonプログラム。



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です