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:
- Take the first two numbers:
0
and1
Our series looks like this:0, 1
- Add them and add the result to our series:
0
+1
=1
Now our series looks like this:0, 1, 1
- 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 getx
, we take1
, and1
and add them:2
. Now our series looks like this:
0, 1, 1, 2
- Chugging along, we want the next number:
0, 1, 1, 2, x
So we take2
and1
, which is3
and that gets us to
0, 1, 1, 2, 3
- Take
3
and2
to get5
:
0, 1, 1, 2, 3, 5
- Take
5
and3
to get8
:
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]