A recursive algorithm is an algorithm that calls itself directly or indirectly. In computer programming, recursive algorithms are very effective in solving a large variety of problems. They often make the description of algorithms concise and easy to understand.
Question 1: The rule for a column number is as follows: 1, 1, 2, 3, 5, 8, 13, 21, and 34. What is the 30th-digit number? Implement with recursion
Copy codeThe Code is as follows: 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: Tower of Hanoi
The Hanoi issue is actually an ancient legend of India.
Brama, the God of heaven and earth (similar to pangu in China), left three diamond rods in a temple, and the first was covered with 64 gold slices, the largest one is in the bottom, and the other is smaller than one, which is stacked in sequence. The monks in the temple place them one by one from this rod to another, the middle stick can be used as a help, but only one can be moved at a time, and the big one cannot be placed on a small surface. The computation results are terrible (the number of rounds being moved) by 18446744073709551615. Even if they have used up their whole life, they won't be able to move the gold.
Requirement: enter a positive integer n, indicating that n disks are on the first column. Output operation sequence in the format of "moving t from x to y ". Each operation row indicates that the disc numbered t on column x is moved to column y. Column numbers are A, B, and C. You need to transfer all the plates from column A to column C with the least operation.
Copy codeThe Code is as follows: 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 + "plate number from" + a + "to" + c );
Else {
Hanio (n-1, a, c, B); // move n-1-1 plate from a to c with B
System. out. println ("mobile" + n + "plate number from" + a + "to" + c); // directly move n to c
Hanio (n-1, B, a, c); // move n-1 plates on B to c using
}
}
}