Card Trick
InterviewTime limit2sMemory limit1024 MB
Given n and m, find the minimum number of deals that always brings the chosen card to the top, which equals the count of base-m digits of n-1.
- Level
Medium4 of 10
- Topics
- Math, Implementation
- Solved
- No attempts yet
Statement
Jim is a magician. More precisely, he is a card magician, and card tricks are his main specialty.
Jim recently invented a new card trick. At the start, the trick uses a deck of distinct cards. Then a spectator picks one card from the deck, memorizes it, puts it back, and the deck is shuffled carefully.
The magic starts here. Jim takes the shuffled deck with the cards face down. Then he deals the cards into piles: the top card goes to pile 1, the second card from the top goes to pile 2, the -th card, if it exists, goes to pile 1 again, the -th to pile 2, and so on. Jim then asks the spectator which pile contains the chosen card. Suppose the card is in pile . Jim collects the piles back into one deck. Pile goes on top of the new deck, with pile under it, and so on up to pile , after which comes pile 1, up to pile . The order of the cards inside each pile is kept, so the first card dealt into a pile is the top card of that pile, the second is under it.
Jim repeats these operations several times until the chosen card is on top of the deck. He claims the card is on top through magic, and it really is on top.
For example, let , the cards are numbered 1 to 6, and . The spectator chose card 1, and the shuffled deck is . The first deal gives piles and , and collecting them gives the deck . The next step gives piles and , and the deck becomes . The chosen card 1 is now on top!
How many times the operation must be repeated depends on the chosen card and on the order of the cards in the deck. Still, there is a minimum number such that for any position of the card in the deck and any chosen card, repeating the deal times puts the chosen card on top.
Write a program that finds the minimum for given and .
Input
The first line contains two integers and ().
Output
Print a single number , the minimum number of deals needed so that the chosen card is certainly on top of the deck.