Given a positive integer n, find the nth Fibonacci number. Fibonacci numbers, when it starts from 0, are calculaed as F(n), where F(1) = 0, F(2) = 1, and F(n) = F(n-1) + F(n-2) for n > 2. Example of first few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
Observe recursive relationship from definition, implement fib(n), when n > 2 return fib(n-1) + fib(n-2). Run recursive calls until when n == 2 return 1 and n < 2 return 0.
def fib(n):
if n < 2:
return 0
if n == 2:
return 1
return fib(n - 1) + fib(n - 2)
n = 5
print(fib(n))
function fib(n) {
if (n < 2) {
return 0;
}
if (n === 2) {
return 1;
}
return fib(n - 1) + fib(n - 2);
}
const n = 5;
console.log(fib(n));