Recursive Fibonacci series java three methods, Fibonacci java

Source: Internet
Author: User

Recursive Fibonacci series java three methods, Fibonacci java

The examples in this article share the code of the java recursive Fibonacci series for your reference. The details are as follows:

First, common writing

public class Demo {    public static void main(String[] args) {     int num1 = 1;     int num2 = 1;     int num3 = 0;     System.out.println(num1);     System.out.println(num2);     for (int i = 1; i < 10; i++) {        num3 = num1 + num2;       num1 = num2;                                                                num2 = num3;       System.out.println(num3);     }   }            } 

Method 2: array-form Recursion

public class DIGUI1 {     public static void main(String[] args) {     int []arr=new int[20];      arr[1]=1;      arr[2]=1;      System.out.print(" "+arr[1]);      System.out.print(" "+arr[2]);     for(int i=3;i<20;i++){        arr[i]=arr[i-1]+arr[i-2];       System.out.print("  "+arr[i]);     }   }  } 

Method 3: recursive writing

Public class Demo {public static int f (int n) throws Exception {if (n = 0) {throw new Exception ("parameter error! ");} If (n = 1 | n = 2) {return 1;} else {return f (n-1) + f (n-2 ); // call yourself} public static void main (String [] args) throws Exception {for (int I = 1; I <= 10; I ++) {System. out. print (f (I) + "");}}}

The biggest problem with recursion is efficiency, but some programs must be written recursively. For example, the famous hanruata question, if anyone can write it out in other ways.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.