Sunday, October 13, 2013

Fibonacci - Golden Ratio

In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are the numbers in the following integer sequence: 0, 1, 1,2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ...

I have always done the one with recursion (or iteration). But mathematics says we could do it with the Golden Ratio ..


var phi = (1 + Math.sqrt(5)) / 2;
var fib_gr = function (n) {
return Math.floor((Math.pow(phi, n) / Math.sqrt(5)) + (1 / 2));
};
for (var i = 1; i < 20; ++i) {
console.log(i, '->', fib_gr(i));
}
var fib_recursion = function (n) {
if (n === 0 || n === 1) {
return n;
}
return fib_recursion(n-1) + fib_recursion(n-2);
};
for (var i = 1; i < 20; ++i) {
console.log(i, '->', fib_recursion(i));
}
view raw fib.js hosted with ❤ by GitHub

No comments: