Two Algorithms of the Fibonacci series:
The Fibonacci series, also known as the Golden split series, refers to such a series: 1, 1, 2, 3, 5, 8, 13, 21 ,...... In mathematics, the Fibonacci series are defined as follows by recursive Methods: F0 = 0, F1 = 1, Fn = F (n-1) + F (n-2) (n> = 2, n, N *)
① Recursion
public static int Fibonacci(int num){ if (num > 0 && num <= 2) return 1; return Fibonacci(num - 1) + Fibonacci(num - 2);}
② Iteration
Public int maid (int num) {if (num> 0 & num <= 2) return 1; // sets f1 to represent the number of num-2, f2 to represent the num-1; current indicates the number of the num Fibonacci queue. Int f1 = 1, f2 = 1, current = 0; for (int I = 3; I <= num; I ++) {current = f1 + f2; f1 = f2; f2 = current;} return current ;}
The algorithm of the fibonacci series and comparison (recursion + non-recursion)
Recursive Algorithms
Int fib (int n) {// calculate the nth Number of the fibonacci series
If (n = 1 | n = 2) return 1;
Else return fib (n-1) + fib (n-2 );
}
Non-recursion
Int fib (int n ){
Int a = 1, B = 1;
If (n = 1 | n = 2) return 1;
For (int I = 3; I <= n; I ++ ){
Int tmp = B;
B = a + B;
A = tmp;
}
Return B;
}
Write a function in java to implement the algorithm of the fibonacci series (, 13)
Class Fibonacci
{
Public static void main (String [] args)
{
Int I;
Int f [] = new int [10];
F [0] = f [1] = 1;
For (I = 2; I <10; I ++)
F [I] = f [I-1] + f [I-2];
For (I = 1; I <= 10; I ++)
{
System. out. println ("F [" + I + "] =" + f [I-1]);
}
}
}