Fibonacci Finder in Javascript

Hi there, the challenges were mentioned in the newsletter today (June 29, 2021), but it seems that the real contest was a couple of years ago. Anyway, I like the idea of doing a challenge now and then. So here’s my Javascript solution (basic level):

const fibo50 = function(num) { // Prints out the 50th number in the Fibonacci sequence let arr = [1,1]; // Starter array, containing the first 2 elements. let i=0; // iterator number while (i <= num) { // loop determines how many Fibonacci numbers there will be in the final array. let lastElem = arr[arr.length -1]; // Captures the last array element let lastButOneElem = arr[arr.length -2]; // Captures the last but one array element. let newElem = lastElem + lastButOneElem; // Calculates the next Fibonacci number. arr.push(newElem); // Adds the next Fibonacci number to the array. i+=1; }; console.log(arr[49]); // Prints out the 50th array element, which has an index of 49. }; fibo50(50);

Regards,
Frank.

2 Likes

This one should satisfy the O(n) requirement:

Using destructured assignment of ES6…

const fibN = n => { a = 1 b = 1 c = 2 while (c < n) { [a, b] = [b, b + a] c++ } return b } console.log(fibN(50))

The same in Python…

def fibN(n): a = 1 b = 1 c = 2 while c < n: a, b = b, b + a c += 1 return b print (fibN(50))
1 Like