Generate Fibonacci Number without ANY looping / recursion

两盒软妹~` 提交于 2019-12-11 15:13:16

问题


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?


回答1:


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));


来源:https://stackoverflow.com/questions/46161784/generate-fibonacci-number-without-any-looping-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!