See the company's written test questions to write the Fibonacci sequence, I wrote a bit of a sneak
What is a Fibonacci sequence: The Fibonacci sequence refers to a sequence of 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946 , 17711,28657,46368 This sequence begins with the second item, each of which equals the sum of the first two.
in particular, the No. 0 item is 0, and the 1th item is the first 1.
Note: At this time a1=1,a2=1,an=a (n-1) +a (n-2) (n>=3,n∈n*)Code:/**
* Created by Zhangjianchao
*/
public class Testalgorithm {
public static void Main (string[] args) {
Fibonacii fibonacii = new Fibonacii ();
System.out.println ("Final times =" +fibonacii.fibonacii (9));
}
}
Class fibonacii{
Public long Fibonacii (long N) {
int fn1 = 1; Item N-1
int fn2 = 1; Item N-2
INT fn = 0; Item n
The first two items of the IF (n<=2) {//series are 1
return 1;
}
Calculates the nth item, while recalculating the first n-2 and n-1 items
for (int i = 0;i < n-2;i++) {
fn = fn1 + fn2;
FN2 = fn1;
FN1 = fn;
System.out.println ("First" + i + "times fn (" + fn + ") = Fn1 (" + fn1 + ") + fn2 (" + fn2 + ")");
}
return FN;
}
}
Algorithm subsection (i)--Fibonacci sequence (Java implementation)