In this post I will be sharing JavaScript code to generate Fibonacci numbers,
✨Recommended Read: Fibonacci – Iterative vs Recursive JS | Matrixread
Check if a given number is a Fibonacci
// Is a Fibonacci number
function isFibonacciNumber(num) {
if (num < 0 || typeof num !== "number") return false;
if (num === 0 || num === 1) return true;
let current = 0;
let next = 1;
while (next < num) {
[current, next] = [next, current + next];
}
return next === num;
}
console.log(isFibonacciNumber(0)); // true
console.log(isFibonacciNumber(3)); // true
console.log(isFibonacciNumber(4)); // false
console.log(isFibonacciNumber(5)); // true
Code language: JavaScript (javascript)Generate required Fibonacci numbers
// Generate Fibonacci numbers from 1 to N
function getFibonacciUpto(num) {
if (num < 0) return [];
if (num === 0) return [0];
if (num === 1) return [0, 1, 1];
let current = 0;
let next = 1;
const result = [0, 1];
while (next <= num) {
[current, next] = [next, current + next];
if (next <= num) result.push(next);
}
return result;
}
console.log(getFibonacciUpto(0)); // [0]
console.log(getFibonacciUpto(1)); // [0,1,1]
console.log(getFibonacciUpto(2)); // [0,1,1,2]
console.log(getFibonacciUpto(3)); // [0,1,1,2,3]
console.log(getFibonacciUpto(4)); // [0,1,1,2,3]
console.log(getFibonacciUpto(5)); // [0,1,1,2,3,5]
// Generate N Fibonacci numbers
function getNFibonacci(num) {
if (num <= 0) return [];
if (num === 1) return [0];
let current = 0;
let next = 1;
const result = [0, 1];
while (result.length < num) {
[current, next] = [next, current + next];
result.push(next);
}
return result;
}
console.log(getNFibonacci(0)); // []
console.log(getNFibonacci(1)); // [0]
console.log(getNFibonacci(2)); // [0,1]
console.log(getNFibonacci(3)); // [0,1,1]
console.log(getNFibonacci(4)); // [0,1,1,2]
console.log(getNFibonacci(5)); // [0,1,1,2,3]
Code language: JavaScript (javascript)Using generator function
/**
* @return {Generator<number>}
*/
var fibGenerator = function* (n) {
let current = 0;
let next = 1;
while (true) {
yield current;
[current, next] = [next, current + next]
}
};
/**
* const gen = fibGenerator();
* gen.next().value; // 0
* gen.next().value; // 1
*/Code language: JavaScript (javascript)Related
- Check if the given number is a Fibonacci in JavaScript
- Generate Fibonacci numbers from 1 to N with JavaScript
- Generate N Fibonacci numbers with JavaScript
- Fibonacci – Iterative vs Recursive JS
- Generate Fibonacci Sequence – 2648
