Home  >  Article  >  Java  >  How to implement Fibonacci sequence in Java

How to implement Fibonacci sequence in Java

王林
王林forward
2023-04-22 16:43:081937browse

The Fibonacci sequence refers to: the last term of the sequence is equal to the sum of the first two terms. In the code, we use a[i]=a[i-1] a[i-2] to achieve this.

Typical rabbit giving birth to baby rabbit problem

Classical problem: There is a pair of rabbits. From the third month after birth, they give birth to a pair of rabbits every month. After the rabbits grow to the third month, they give birth to another pair every month. Assume that each pair of rabbits does not die. Programming Realize the number of rabbit logs for each month.

​Code example:

Core code, Fibonacci sequence (the last term is equal to the sum of the first two):

publicstaticvoidgetTuTu(int[]tutu,intn){

​if(n==1){

System.out.println("The number of rabbit pairs in the first month is 1");

}elseif(n==2){

System.out.println("The number of rabbits in the second month is 1");

}else{

tutu[0]=1;

tutu[1]=1;

System.out.println("The number of rabbit pairs in the first month is 1");

System.out.println("The number of rabbits in the second month is 1");

​for(inti=2;i

tutu[i]=tutu[i-1] tutu[i-2];//array records rabbit logarithm

System.out.println("(i 1) "The rabbit logarithm of the month is" tutu[i]);

}

}

}

Complete code:

​packageday191125;

​importjava.util.Scanner;

publicclassTuZi{

publicstaticvoidmain(String[]args){

Scannerinput=newScanner(System.in);

​while(true){

System.out.println("=========");

System.out.println("Enter the month to find the rabbit:");

​intn=input.nextInt();

​if(n<=0){

System.out.println("Input error, re-enter");

​continue;

}

int[]tutu=newint[n];

​getTuTu(tutu,n);

}

}

publicstaticvoidgetTuTu(int[]tutu,intn){

​if(n==1){

System.out.println("The number of rabbit pairs in the first month is 1");

}elseif(n==2){

System.out.println("The number of rabbits in the second month is 1");

}else{

tutu[0]=1;

tutu[1]=1;

System.out.println("The number of rabbit pairs in the first month is 1");

System.out.println("The number of rabbits in the second month is 1");

​for(inti=2;i

tutu[i]=tutu[i-1] tutu[i-2];

System.out.println("(i 1) "The rabbit logarithm of the month is" tutu[i]);

}

}

}

}

The above is the detailed content of How to implement Fibonacci sequence in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete