Java tip 01 -- Recursive iteration to complete the Fibonacci

Source: Internet
Author: User

I had a rest today, So I went online and checked my post. I posted a post on Baidu Post Bar, writing how to implement the Fibonacci series recursively, after that, I thought it would be a waste to do this simple thing with recursion. So I wrote this article to implement how to replace recursion with iteration.

First, we will introduce the series of Fibonacci. In fact, it is very simple: 1, 1, 2, 3, 5, 8, and 13. Except for the first and second numbers, the nth number is the sum of the first two numbers, so straightforward, you should understand it!

Public class method {

Public static void main (string ARGs []) {
System. Out. println (test (5 ));
}

Public static long test (INT index ){
If (index <1 ){
System. Out. println ("invalid parameter !!!!!! ");
Return 0;
}
If (Index = 1 | Index = 2 ){
Return 1;
} Else {
Long F1 = 1l;
Long F2 = 1l;
Long F = 0l;
For (INT I = 0; I <index-2; I ++ ){
F = F1 + F2;
F1 = F2;
F2 = F;
}
Return F;
}
}
}

In fact, it is very simple. I will not add comments here, which is a waste of space and a joke. In fact, it is a good habit to add comments when writing code. I hope that the children's shoes can avoid recursion as much as possible.

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.