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)