Move n disks from a source peg to a destination peg using an auxiliary peg, never placing a larger disk on a smaller one.
Classic recursion: move n-1 disks to the auxiliary peg, move the largest disk to the destination, then move the n-1 disks from auxiliary to destination. It requires exactly 2^n - 1 moves — O(2^n), an intrinsic property of the problem, not an inefficiency.
public static void hanoi(int n, char from, char aux, char to) {
if (n == 1) { System.out.println("Move disk 1 from " + from + " to " + to); return; }
hanoi(n - 1, from, to, aux);
System.out.println("Move disk " + n + " from " + from + " to " + to);
hanoi(n - 1, aux, from, to);
}function hanoi(n, from, aux, to) {
if (n === 1) { console.log('Move disk 1 from ' + from + ' to ' + to); return; }
hanoi(n - 1, from, to, aux);
console.log('Move disk ' + n + ' from ' + from + ' to ' + to);
hanoi(n - 1, aux, from, to);
}def hanoi(n, frm, aux, to):
if n == 1:
print(f'Move disk 1 from {frm} to {to}')
return
hanoi(n - 1, frm, to, aux)
print(f'Move disk {n} from {frm} to {to}')
hanoi(n - 1, aux, frm, to)Tower of Hanoi is the textbook demonstration of recursive problem decomposition and of exponential growth (2^n) you can reason about precisely.
For n = 64 disks the program would run essentially forever. Is that a bug in your code?