Skip to content

Instantly share code, notes, and snippets.

@gauravds
Last active October 3, 2025 08:59
Show Gist options
  • Select an option

  • Save gauravds/26731db1989223debd53deedef38ea2d to your computer and use it in GitHub Desktop.

Select an option

Save gauravds/26731db1989223debd53deedef38ea2d to your computer and use it in GitHub Desktop.

Revisions

  1. gauravds revised this gist Oct 3, 2025. 1 changed file with 1 addition and 16 deletions.
    17 changes: 1 addition & 16 deletions fib.js
    Original file line number Diff line number Diff line change
    @@ -18,22 +18,7 @@
    */

    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);
    }
    return -1
    }

    /** Console tests (value, isExpected) */
  2. gauravds revised this gist Oct 3, 2025. No changes.
  3. gauravds created this gist Oct 3, 2025.
    46 changes: 46 additions & 0 deletions fib.js
    Original 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