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.