Find the nth Fibonacci Number
Instructions
Write a function that returns the nth number in the Fibonacci sequence. The Fibonacci sequence is defined as follows:
- F(0) = 0
- F(1) = 1
- F(n) = F(n-1) + F(n-2) for n > 1
Examples
Here are a few examples to illustrate how the fibonacci
function works:
Example 1
Input: n = 1
Output: 1
Example 2
Input: n = 5
Output: 5
Example 3
Input: n = 10
Output: 55
Solution
The example solution provided demonstrates a function called fibonacci
that returns the nth number in the Fibonacci sequence. The function uses a loop to calculate the sequence iteratively, storing the previous two numbers and updating them as it progresses through the sequence.
Find Fibonacci
const fibonacci = (n) => {
if (n < 0) return null;
if (n === 0) return 0;
if (n === 1) return 1;
let a = 0, b = 1, i = 2;
while (i <= n) {
let temp = a + b;
a = b;
b = temp;
i++;
}
return b;
}