Usage analysis of Java recursive algorithms

  • 2020-04-01 01:41:57
  • OfStack

A recursive algorithm is one that calls itself directly or indirectly. In computer programming, recursive algorithm is very effective to solve a large class of problems, it often makes the description of the algorithm concise and easy to understand.

Question 1: the rules for a column number are: 1, 1, 2, 3, 5, 8, 13, 21, 34. What is the 30th digit? Use a recursive implementation


public class FibonacciSequence {
    public static void main(String[] args){
        System.out.println(Fribonacci(9));

    }
    public static int Fribonacci(int n){
        if(n<=2)
            return 1;
        else
            return Fribonacci(n-1)+Fribonacci(n-2);

    }
}

Question 2: the Hanover tower problem

The hannotta problem is actually an old Indian legend.

(beginning god bourgogne ramah and pangu is the same as the Chinese god) in a temple left three rods of diamond, the first piece of gold set with 64 round, one of the biggest under it, other than a small, in turn, fold up, all the monks in the temple tirelessly to put them one by one from this bar moved to another rod, available in the middle of a rod as a help, but can only move one at a time, and not on the small face. The result was so horrible (number of moves) that the monks could not move the gold even if they had spent their whole lives.

Requirement: enter a positive integer n to indicate that there are n disks on the first column. Output a sequence of operations in the format "move t from x to y". Each operation line indicates that the plate number t on column x is moved to column y. The columns are numbered A, B, C, and you need to transfer all the plates from pillar A to pillar C with minimal effort.


public class Hanio {
    public static void main(String[] args){
        int i=3;
        char a ='A',b='B',c='C';
        hanio(i,a,b,c);
    }
    public static void hanio(int n,char a,char b,char c){
        if(n==1)
            System.out.println(" mobile "+n+" Number plate from "+a+" to "+c);
        else{
            hanio(n-1,a,c,b);//I'm going to move n minus 1 plates from a to c with the help of b
            System.out.println(" mobile "+n+" Number plate from "+a+" to "+c);//And then I'm going to move n directly to c
            hanio(n-1,b,a,c);//I'm going to take n minus 1 plates from b and move them from a to c
        }
    }
}


Related articles: