Implement Fibonacci sequence using javascript

藏色散人
Release: 2022-10-12 16:55:23
Original
8698 people have browsed it

Javascript method to implement Fibonacci sequence: 1. Use recursive method to implement, code such as "function fib(n){...}"; 2. Use for loop to implement, code such as "for( var i=2;i

Implement Fibonacci sequence using javascript

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript implements the Fibonacci sequence

The Fibonacci sequence, also known as the golden section sequence, refers to such a sequence: 1, 1, 2, 3, 5, 8, 13, 21... Starting from the 3rd number, each number is equal to the sum of the two numbers before it

Method 1: Recursion

function fib(n){ if(n==1 || n==2){ return 1; } return fib(n-1) + fib(n-2); }
Copy after login

Method 2: for Loop implementation

function fb(n){ var res = [1,1]; if(n == 1 || n == 2){ return 1; } for(var i=2;i
        
Copy after login

or

function fb(n){ var a,b,res; a = b = 1; for(var i=3;i<=n;i++){ res = a + b; a = b; b = res; } return res; }
Copy after login

[Recommended learning:javascript advanced tutorial]

The above is the detailed content of Implement Fibonacci sequence using javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!