fibonacci iterative javascript code example
Example 1: fibonacci javascript
function Fibonacci(num){
var before = 0;
var actual = 1;
var next = 1;
for(let i = 0; i < num; i++){
console.log(next)
before = actual + next;
actual = next
next = before
}
}
Fibonacci(100);
Example 2: javascript fibonacci
function fibonacci(n) {
return n < 1 ? 0
: n <= 2 ? 1
: fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(4));
Example 3: js fibonacci sequence
var i;
var fib = [];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= 10; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
console.log(fib[i]);
}
Example 4: 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)
})