Exercises 1

Fibonacci

The Fibonacci numbers 1, 1, 2, 3, 5, 8, 13 ... are defined by recursion like this:

a(n) = 1 for n=1, n=2 a(n) = a(n-1) + a(n-2) for n>2

Write a function to calculate the n’th Fibonacci number.

First - sketch your function on paper.
Next – implement a program to test it.
Last – make a drawing to show the function-calls involved in calculating the seventh Fibonacci number.


See Solution:

function FibonacciRecusive(n){ if(n===1 || n===2){ return 1; }else{ return FibonacciRecusive(n-1)+FibonacciRecusive(n-2); } } function Fibonacci(n){ var i, num1 = 1, num2 = 1, nextnum; for(i=2;i<n;i++){ nextnum = num1+num2; num1 = num2; num2 = nextnum; } return num2; } Result :