(Fibonacci Summary) Write a method to generate the nth Fibonacci number (CC150 8.1)

Source: Internet
Author: User

Based on the CC150 solution and introduction to Java Programming Summary:

There are two ways of using recursion and iteration

The code provided by CC150 is relatively concise, but some details need to be analyzed.

Now run the code directly, enter the value of n (where number is substituted to avoid confusion with N in the method), and you can derive Fibonacci numbers.

The code is as follows:

/*CC150 8.1 Write a method to generate the nth Fibonacci number Author:mengyang Rao Note:use the methods , iteration and recursion date:2015-02-25 23:56:00*/ImportJava.util.Scanner; Public classTestfibonacci { Public Static voidMain (string[] args) {Scanner input=NewScanner (system.in); System.out.print ("Please enter N:"); intNumber =Input.nextint (); System.out.println ("The iteration number is:" + Fibonacci (number) + "\ n value is:" +Number ); System.out.println ("The recursion number is:" + fibo (number) + "\ n value is:" +Number ); }//version:recursion     Public Static LongFiboLongN) {if(n = = 0)         return0; Else if(n = = 1)        return1; Else if(N > 1)        returnFibo (n-1) + Fibo (n-2); Else         return-1;}//version:iteration     Public Static LongFibonacciLongN) {intA = 0, B = 1; if(N < 0)             return-1; Else if(n = = 0)            return0;  for(inti = 3; I <= N; i++) {            intc = A +b; A=b; b=C; }        returnb; }}

(Fibonacci Summary) Write a method to generate the nth Fibonacci number (CC150 8.1)

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.