Fibonacci Sequence (recursive, non-recursive algorithm)

Source: Internet
Author: User
Tags time limit

Topic

Fibonacci number, also known as the Fibonacci sequence (Italian: Successione di Fibonacci), also known as the Golden Section, Faipot, the number of Faipot, Sinorhizobium fredii series, refers to such a series: 1, 1, 2, 3, 5, 8, 13, 、...... In mathematics, the Fibonacci sequence is defined recursively as follows: F0=0,f1=1,fn=fn-1+fn-2 (n>=2,n∈n*), in words, is the Fibonacci sequence starting with 0 and 1, followed by the Fibonacci sequence coefficients are added by the previous two numbers.

Limit

Time limit: 1 seconds space limit: 32768K

 PackageCom.algorithm;ImportJava.util.Scanner;/*** We all know that the Fibonacci sequence is now required to enter an integer n, please output the nth of the Fibonacci sequence. n<=39 * @ Date: June 30, 2018 PM 10:11:43 * @Chendb*/ Public classFibonacci { Public Static voidMain (string[] args) {Scanner Scanner=NewScanner (system.in); intn =Scanner.nextint ();        System.out.println (Fibonaccirecursion (n));    System.out.println (Fibonacci (n)); }        /*** Recursive algorithm *@paramN *@return     */     Public Static intFibonaccirecursion (intN) {if(N < 1) {            return0; }                if(n = = 1 | | n = = 2) {            return1; }                returnFibonaccirecursion (n-1) + fibonaccirecursion (n-2); }        /*** Non-recursive algorithm *@paramN *@return     */     Public Static intFibonacciintN) {if(N < 1) {            return0; }                if(n = = 1 | | n = = 2) {            return1; }                intresult = 1; intPreresult = 1;//n-2 Items        intCurrentresult = 1;//n-1 Items         for(inti = 3; I <= N; i++) {result= Preresult + Currentresult;//n = f (n-1) + f (n-2)Preresult = Currentresult;//f (n-2) = f (n-1)Currentresult = result;//f (n-1) = n        }        returnresult; }}
View Code

Fibonacci Sequence (recursive, non-recursive algorithm)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.