fizz buzz | http://wiki.c2.com/FizzBuzzTest | Cell 2 | Search

The isFib function checks if a given number is a Fibonacci number by generating Fibonacci numbers until it finds a match or exceeds the input number. It returns true if the number is a Fibonacci number and false otherwise, as demonstrated in the provided example usage.

Cell 1

function isFib(num) {
    let last = 0;
    let next = 1;
    while (next <= num) {
        let newThingThatIsAVariable = last + next;
        if (newThingThatIsAVariable === num) { return true; }
        last = next;
        next = newThingThatIsAVariable;
    }
    return false;
}

isFib(4);

// 0 + 1 = 1
// 1 + 1 = 2
// 1 + 2 = 3
// 2 + 3 = 5
// 3 + 5 = 8

What the code could have been:

/**
 * Checks if a given number is a Fibonacci number.
 * 
 * @param {number} num The number to check.
 * @returns {boolean} True if the number is Fibonacci, false otherwise.
 */
function isFibonacci(num) {
    // Check if the number is negative or non-integer
    if (num < 0 || num % 1!== 0) {
        return false;
    }

    // Initialize the first two numbers in the Fibonacci sequence
    let a = 0;
    let b = 1;

    // Continue the loop until the next number exceeds the given number
    while (b <= num) {
        // Check if the current number is the Fibonacci number we're looking for
        if (b === num) {
            return true;
        }

        // Calculate the next number in the Fibonacci sequence
        [a, b] = [b, a + b];
    }

    // If the loop ends without finding the number, it's not Fibonacci
    return false;
}

console.log(isFibonacci(4)); // false
console.log(isFibonacci(8)); // true

Function: isFib

Purpose

Checks if a given number is a Fibonacci number.

Parameters

Return Value

Algorithm

  1. Initializes two variables: last and next, to the first two Fibonacci numbers (0 and 1).
  2. Enters a loop that continues as long as next is less than or equal to the input num.
  3. Inside the loop:
  4. If the loop completes without finding a match, returns false.

Example Usage

isFib(4); // Returns: false
isFib(5); // Returns: true