This page is still under construction.

Parts of this page are still being built. What you see may change.

One Move from Towers of Hanoi

Interview

Time limit3sMemory limit128 MB

Summary
Given n disks and an index k, report the disk and the source and destination posts of the kth move in the classic recursive Hanoi solution.
Level

Medium5 of 10

Topics
Recursion, Bit manipulation, Math
Solved
No attempts yet

Problem

This problem is about the classic Towers of Hanoi. There are three posts and a collection of circular disks. Call the number of disks nn. The disks have different sizes, with no two sharing a radius, and there is one rule: never put a bigger disk on top of a smaller one. Number the disks from 1 (smallest) to nn (biggest) and name the posts A, B, and C. All the disks start on post A, and the goal is to move them to post C one at a time, again never putting a bigger one on top of a smaller one. The well-known solution recursively moves the top n−1n-1 disks from A to B, moves the bottom disk from A to C directly, then recursively moves those n−1n-1 disks from B to C.

Pseudocode for a recursive solution to the classic Towers of Hanoi problem:

move(num_disks, from_post, spare_post, to_post)
    if (num_disks == 0)
        return
    move(num_disks - 1, from_post, to_post, spare_post)
    print ("Move disk ", num_disks, " from ",
        from_post, " to ", to_post)
    move(num_disks - 1, spare_post, from_post, to_post)

Given kk and nn, determine the kkth move made by the algorithm above.

Input

Each line of input holds two integers kk and nn. A line with two zeros marks the end of input.

All input is valid. kk and nn are positive integers, k<2nk < 2^n so that a kkth move exists, and n≤60n \le 60 so that the answer fits in a 64-bit integer type.

Output

For each test case, print the kkth move made by the algorithm above. Follow this format exactly: Case, one space, the case number, a colon and one space, then the answer for that case given as the number of the disk, the name of the from_post, and the name of the to_post, with one space separating the parts of the answer. Do not print any trailing spaces.

Examples1

  1. Example 1

    Input
    1 3
    5 3
    8 4
    0 0
    
    Expected output
    Case 1: 1 A C
    Case 2: 1 B A
    Case 3: 4 A C