0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【プログラミング初心者】Swift練習問題~フィボナッチ数列~回答例

Last updated at Posted at 2020-06-08

フィボナッチ数列

回答例

func getFibonacci(limit: Int) -> [Int] {
    guard limit >= 0 else {
        return []
    }
    // 現在の値(初期値: a[1] = 1)
    var currentNumber = 1
    // 前項の値(初期値: a[0] = 0)
    var preNumber = 0
    
    var fibonacci: [Int] = [preNumber]
    
    while currentNumber <= limit {
        fibonacci.append(currentNumber)
        // 更新
        let nextNumber = currentNumber + preNumber
        preNumber = currentNumber
        currentNumber = nextNumber
    }
    return fibonacci
}

解説

フィボナッチ数列の漸化式はa[n+1]=a[n]+a[n-1]と表されます。
a[0]=a[-1]+a[-2]a[1]=a[0]+a[-1]は計算できないためそれぞれ初期値として0, 1という値が与えられます。
現在の判定される値としてcurrentNumber前項の値としてpreNumberを変数として定義しそれぞれa[0], a[1]として初期化します。

あとはwhile currentNumber <= limitでリミットに達するまでループを回します。
判定処理後、配列に追加し次の値に更新しています。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?