0

Using ES5 as pseudocode / example:

var gr = 1.61803398875;
function fib(v) { // fib without recursion
    if(v < 2) return v;
    return Math.round(((v-2) + (v-1)) * gr);
}

function fibr(v) { // fib with recursion
        if(v < 2) return v;
    return fibr(v-2) + fibr(v-1);
}

console.clear();
console.log(fib(0), fibr(0)); // 0 0
console.log(fib(1), fibr(1)); // 1 1
console.log(fib(2), fibr(2)); // 2 1
console.log(fib(3), fibr(3)); // 5 2
console.log(fib(4), fibr(4)); // 8 3
console.log(fib(5), fibr(5)); // 11 5
console.log(fib(6), fibr(6)); // 15 8
console.log(fib(7), fibr(7)); // 18 13
console.log(fib(8), fibr(8)); // 21 21
console.log(fib(9), fibr(9)); // 24 34

How can I calculate a fibonacci number without any sort of looping / recursion?

Jacksonkr
  • 31,583
  • 39
  • 180
  • 284

1 Answers1

2

While writing this question I did additional research as I had new ideas, which happens a LOT of the time.

I found this answer which has the math for a fibonacci number without recursion

Fn = (φn − (−φ)−n) / √5, where φ = (1 + √5) / 2 ≈ 1.6180339887

Converted to ES5 it looks like this:

var gr = 1.61803398875;
function fib(v) { // fib without recursion
    if(v < 2) return v;
    // return Math.round(((v-2) + (v-1)) * gr);
    return Math.floor((Math.pow(gr, v) - (-gr)) / Math.sqrt(5));
}

And short ES6 for those who want it

let gr = 1.61803398875;
let fib=(v)=>Math.floor((Math.pow(gr,v)-(-gr))/Math.sqrt(5));
Jacksonkr
  • 31,583
  • 39
  • 180
  • 284