Last active
October 3, 2025 08:59
-
-
Save gauravds/26731db1989223debd53deedef38ea2d to your computer and use it in GitHub Desktop.
Revisions
-
gauravds revised this gist
Oct 3, 2025 . 1 changed file with 1 addition and 16 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -18,22 +18,7 @@ */ function findFibIndex(n) { return -1 } /** Console tests (value, isExpected) */ -
gauravds revised this gist
Oct 3, 2025 . No changes.There are no files selected for viewing
-
gauravds created this gist
Oct 3, 2025 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,46 @@ /** * Assignment: Find Fibonacci Index * * Instructions: * 1. Implement the function `findFibIndex(n)` that returns the 1-based index of * the number `n` in the Fibonacci sequence. * 2. If the number does not exist in the sequence, return -1. * 3. The Fibonacci sequence starts with: 0, 1, 1, 2, 3, 5, 8, ... * 4. Do not use recursion — use iterative logic instead. * 5. Write and run console tests to verify your solution. * * Examples: * findFibIndex(5) → 6 * findFibIndex(4) → -1 * findFibIndex(21) → 9 * findFibIndex(0) → 1 * findFibIndex(-5) → -1 */ function findFibIndex(n) { let fib = [0, 1, 1, 2, 3, 5, 8]; const last = fib[fib.length - 1]; if (n <= last) { for (let i = 0; i < fib.length; i++) { if (fib[i] === n) return i + 1; // 1-based index } return -1; } for (let i = fib.length; ; i++) { const next = fib[i - 1] + fib[i - 2]; if (next === n) return i + 1; if (next > n) return -1; fib.push(next); } } /** Console tests (value, isExpected) */ console.log(findFibIndex(5), findFibIndex(5) === 6); // 6 true console.log(findFibIndex(4), findFibIndex(4) === -1); // -1 true console.log(findFibIndex(21), findFibIndex(21) === 9); // 9 true console.log(findFibIndex(0), findFibIndex(0) === 1); // 1 true console.log(findFibIndex(1), findFibIndex(1) === 2); // 2 true console.log(findFibIndex(144),findFibIndex(144)=== 13); // 13 true console.log(findFibIndex(-5), findFibIndex(-5) === -1); // -1 true