生成斐波那契数,而无需任何循环/递归 [英] Generate Fibonacci Number without ANY looping / recursion

查看:83
本文介绍了生成斐波那契数,而无需任何循环/递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ES5作为伪代码/示例:

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?

推荐答案

在撰写此问题时,由于有了新的想法,我做了一些额外的研究.

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

我发现此答案具有斐波那契数的数学原理而无需递归

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

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

转换为ES5看起来像这样:

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

为想要的人简短介绍ES6

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

这篇关于生成斐波那契数,而无需任何循环/递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆