Three java programming methods implement the Fibonacci sequence
- 2021-01-25 07:31:48
- OfStack
Write a program to output the first 20 items of the Fibonacci sequence on the console, with 5 newlines for each item
//java programming: 3 ways to implement the Fibonacci sequence
// The first method is:
public class Demo2 {
// define 3 Three variable method
public static void main(String[] args) {
int a = 1, b = 1, c = 0;
System.out.println(" Before the Fibonacci sequence 20 Items as follows: ");
System.out.print(a + "\t" + b + "\t");
// Because there are two more in front 1 , 1 so i<=18
for (int i = 1; i <= 18; i++) {
c = a + b;
a = b;
b = c;
System.out.print(c + "\t");
if ((i + 2) % 5 == 0)
System.out.println();
}
}
}
//java programming: 3 ways to implement the Fibonacci sequence
// The second method is:
public class Demo3 {
// Define array methods
public static void main(String[] args) {
int arr[] = new int[20];
arr[0] = arr[1] = 1;
for (int i = 2; i < arr.length; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}
System.out.println(" The front of the Fibonacci sequence 20 The items are as follows: ");
for (int i = 0; i < arr.length; i++) {
if (i % 5 == 0)
System.out.println();
System.out.print(arr[i] + "\t");
}
}
}
//java programming: 3 ways to implement the Fibonacci sequence
// 3 methods:
public class Demo4 {
// Use recursive methods
private static int getFibo(int i) {
if (i == 1 || i == 2)
return 1;
else
return getFibo(i - 1) + getFibo(i - 2);
}
public static void main(String[] args) {
System.out.println(" The front of the Fibonacci sequence 20 Items as follows: ");
for (int j = 1; j <= 20; j++) {
System.out.print(getFibo(j) + "\t");
if (j % 5 == 0)
System.out.println();
}
}
}
This rabbit problem is essentially a Fibonacci sequence: 1 pair of rabbits, 1 pair of rabbits born every month from the birth of the third month, and 1 pair of rabbits born every month after the birth of the third month, if no rabbits die, what is the total number of rabbits per month ? , now from the variable, array, recursion 3 points of view to solve this puzzle, of course, there are other methods, the same 1 question with a variety of different ideas to think about the solution, but also the comprehensive use of knowledge of the exercise.