Start learning Java, the basic knowledge of the evil fill!
The Fibonacci sequence , also known as the Golden Section, refers to a sequence of numbers: 1, 1, 2, 3, 5, 8, 13, 、...... Mathematically, the Fibonacci sequence is defined as a recursive method: F0=0,f1=1,fn=f (n-1) +f (n-2) (n>=2,n∈n*).
Title: Classical Questions: There are a pair of rabbits, from the 3rd month after birth a pair of rabbits each month, the rabbit long to the third month after the birth of a pair of rabbits, if the rabbit is not dead, ask each month the total number of rabbits?
The following are the Java code implementations (recursion and recursion):
Import Java.util.Scanner;
public class Fibonacci {
public static void Main (string[] args) {
System.out.println ("Please enter a number");
Scanner in = new Scanner (system.in);
int n = in.nextint ();
System.out.println ("Recursion: the number of +n+" is: "+fibonacci1 (N)");
System.out.println ("Recursion: the number of +n+" is: "+fibonacci2 (N)");
}
Recursive implementation method
public static int fibonacci1 (int n) {
if (n<=0) {
return 0;
}
else if (n<=2) {
return 1;
}
else{
Return (FIBONACCI1 (n-1) +fibonacci1 (n-2));
}
}
public static int Fibonacci2 (int n) {
if (n<=0) {
return 0;
}
else if (n<=2) {
return 1;
}
else{
int temp=0,num1=1,num2=1;
for (int i=3;i<=n;i++) {
temp=num1+num2;
num1=num2;
Num2=temp;
}
return temp;
}
}
}
Welcome to the Exchange!
Java Basic algorithm interview title: 1 Fibonacci Sequence