#Quiz08 – Fibonacci Numbers

Here are the instructions:

Write a function that calculates returns the “nth” Fibonacci number where we define a function over the Fibonacci numbers mapping the naturals (starting with zero) to the Fibonacci series. So fibonacci(0) returns 0, fibonacci(1) returns 1, fibonacci(2) returns 1 and so on. Note that we are using the modern definition where the sequence starts with zero. You should try to implement this with two solutions: one with a loop and one with recursion. Which do you think is “better”, which looks more “elegant”, which is more “efficient”?

  • I found it easier to write a recursive function ( with if, elif, else statements). Indeed, we know that the fibonacci number of 0 is 0, and that the fibonacci number of 1 is 1. Then the fibonacci number of a number is equal to the sum to the two preceding fibonacci numbers. For instance the fibonacci number of 3 is equal to the sum of the fibonacci number of 2 + the fibonacci number of 1.
  • The function with a loop was harder to get. We need to insert the same if, else statement in the function because of the fibonacci numbers of 0 and 1. Then we need to set the local variables x=0 and y=1.
  • What the for loop in this function does is that it re assigns the value of y and z to x and y respectively in order to loop the process of adding the following fibonacci numbers.

Leave a comment