Coding Challenge Practice - Question 114
Source: Dev.to
Problem Description
The task is to find the n-th Fibonacci number. Fibonacci numbers are the sum of the previous two numbers in the sequence, which starts with 0 and 1.
Solution Explanation
- If n is 0 or 1, the result is n itself.
- Otherwise, iterate from 2 up to n, keeping track of the two most recent numbers (
prevandcurr). - In each iteration compute
next = prev + curr, then shift the variables:prev = curr,curr = next. - After the loop,
currholds the n-th Fibonacci number.
Reference Implementation (JavaScript)
function fib(n) {
// Return n for the base cases 0 and 1
if (n <= 1) return n;
let prev = 0;
let curr = 1;
// Build the sequence up to n
for (let i = 2; i <= n; i++) {
const next = prev + curr;
prev = curr;
curr = next;
}
return curr;
}