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.
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
/**
* 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
isFib
Checks if a given number is a Fibonacci number.
num
: The number to be checked.true
if the number is a Fibonacci number, false
otherwise.last
and next
, to the first two Fibonacci numbers (0 and 1).next
is less than or equal to the input num
.last
and next
.num
. If so, returns true
.last
and next
with the new values.false
.isFib(4); // Returns: false
isFib(5); // Returns: true