fibonacci javascript question code example
Example 1: javascript fibonacci example
function fibonacci(nums) {
let fib = [0, 1];
let data = [];
for(let i = 2; i <= nums; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
data.push(fib[i]);
}
return data;
}
Example 2: js to confirm fibonnaci
function isFibonacci(n) {
var fib,
a = (5 * Math.pow(n, 2) + 4),
b = (5 * Math.pow(n, 2) - 4)
var result = Math.sqrt(a) % 1 == 0,
res = Math.sqrt(b) % 1 == 0;
if (result || res == true)
{
fib = Math.round(n * 1.618);
console.log("The next Fibonacci number is " + fib);
} else {
console.log(`The given number ${n} is not a fibonacci number`);
}
}
$('#fib').on("keyup change", function() {
isFibonacci(+this.value)
})