Fibonacci Sequence Explained

If you’re not familiar with the Fibonacci sequence, the gist is that each number is the sum of the two numbers before it, starting from 0 and 1.

Step by step, it would look like this:

  1. Take the first two numbers: 0 and 1
    Our series looks like this: 0, 1
  2. Add them and add the result to our series: 0 + 1 = 1
    Now our series looks like this: 0, 1, 1
  3. In order to get the next number, you add the two numbers before it. We’ll put in an x to represent the number we want: 0, 1, 1, x
    To get x, we take 1, and 1 and add them: 2. Now our series looks like this:
    0, 1, 1, 2
  4. Chugging along, we want the next number:
    0, 1, 1, 2, x
    So we take 2 and 1, which is 3 and that gets us to
    0, 1, 1, 2, 3
  5. Take 3 and 2 to get 5:
    0, 1, 1, 2, 3, 5
  6. Take 5 and 3 to get 8:
    0, 1, 1, 2, 3, 5, 8

and so on.

As a function it looks like this:

// Get the Fibonacci number at num
func fibonacci(num: Int) -> Int {
    if num == 0 {
        return 0
    }

    if num < 1 {
        return 1
    }

    return fibonacci(num: num - 1) + fibonacci(num: num - 2)
}

We can get a sequence by calling the above function in a loop:

// Get the first num numbers in the Fibonacci sequence
func fibonacciSequence(num: Int) -> [Int] {
    var series = [Int]()
    for i in 0…num - 1 {
        let fibNum = fibonacci(num: i)
        series.append(fibNum)
    }

    return series
}

So if we feed 7 to our function, we should get a return value of [0, 1, 1, 2, 3, 5, 8]

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.