The Nth item of the Fibonacci sequence of the Java recursive algorithm

The Fibonacci sequence, also known as the golden section sequence, was proposed by the Italian mathematician Leonardo Fibonacci. The Fibonacci sequence refers to such a sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, ..., this sequence starts from the 3rd term, and each term is equal to the previous two Sum. Mathematically, the ways in which the Fibonacci sequence can be recursed are defined as follows:

F(1)=1,F(2)=1, F(n)=F(n – 1)+F(n – 2)(n ≥ 3,n ∈ N*)

1. The recursive termination condition of the Fibonacci sequence is
obviously easy to see. By observing the definition of the Fibonacci sequence, we can easily find that when n=1 or n=2, it is the recursive termination condition of the Fibonacci sequence. At this time, the specific value of the Fibonacci sequence can be given.

2. The processing method when the Fibonacci sequence recursively terminates is the
same, based on the recursive definition of the Fibonacci sequence, when the Fibonacci sequence reaches the termination condition n=1 or n=2, we can also easily find that Corresponding to  F (1)=1, F (2)=1, this is the corresponding value of the Fibonacci sequence when the recursion terminates.

3. Recursive repetition logic extraction
of Fibonacci sequence According to the mathematical definition of Fibonacci sequence, F (n)= F (n – 1)+ F (n – 2) ( n  ≥ 3, n  ∈ N*) , that is, when  n  ≥ 3, the value of this item in the Fibonacci sequence is equal to the sum of the values ​​of the previous two items, so that solving a relatively large Fibonacci sequence can be transformed into solving a Fibonacci sequence with a smaller value. The value of the Bonacci sequence, there is repeated logic in it that can be reused recursively.

code show as below:

import java.util.Scanner;

public class Test24 {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请斐波那契数列的项数:");
        int num=scanner.nextInt();
        int s=func(num);
        System.out.println("斐波那契数列的第"+num+"项为"+s);
    }

    private static int func(int num) {
        if(num==1||num==2){
            return 1;
        }else{
            return func(num-1)+func(num-2);
        }
    }
}

Achieving the result:

 

Guess you like

Origin blog.csdn.net/m0_62218217/article/details/121585426