Recursive implementation and non-recursive implementation of Fibonacci

Source: Internet
Author: User

Recursive implementation is very good to achieve, mainly is the idea of recursion and division.

A non-recursive implementation can be implemented using an array, the general recursion is to put the initial value at the end of the use, non-recursive can be considered as the initial value (FIB (0) =0;fib (1) = 1;) based on the use of loops to calculate.

Code:

public class Fibonacci{public int getresultbyrecursion (int n) {if (n = = 0) {return 0;} else if (n = = 1) {return 1;} Else{return GetResult (n-1) +getresult (n-2);}} public int GetResult (int n) {int[] temp = new Int[n];temp[0] = 0;temp[1] = 1;for (int i=2;i<temp.length;i++) {Temp[i] = Te MP[I-1] + temp[i-2];} return temp[n-1];} public static void Main (string[] args) {int n = 20; Fibonacci obj = new Fibonacci (); System.out.println ("The recursion result is" +obj.getresultbyrecursion (n)); System.out.println ("The nonrecursion result is" +obj.getresult (n));}}

Share!

Recursive implementation and non-recursive implementation of Fibonacci

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.