How does the three piles magic trick work? When I was growing up, my parents taught me a simple magic trick that consisted in making three piles of cards and guessing my card, even when they hadn't even touched the deck. 
The trick in itself is not too complicated. It goes like this (it may be better explained here):


*

*Reduce the deck to an odd number of cards multiple of 3 (so there will be a same number of cards in each pile; I use a Spanish deck reduced to 39 cards, but normally do it with 21 cards to shorten the process.)

*Ask a person to pick a card from the deck, remember it, and shuffle the deck.

*Make 3 piles of cards, dealing successive cards to to pile $A$, $B$, $C$, $A$, $B$, ... in turn (and face up).

*When you are done, ask the person to point to the pile that contains their card.

*Put that pile in between the other piles.

*Repeat steps 3-5 two more times (for a total of 3 times).

*The picked card will always be in the center of the deck (e.g. in the 11th position if 21 cards). Now that you know it, make some "presentation" to make it look like magic.


This is really a mathematical thing. There is no sleight-of-hand, preparation, or diversion to trick the person into picking a card or doing anything special.
Why does the selected card always end up in the center of the deck? What is the mathematical proof for this trick?
And, out of curiosity, would this trick work for any number of cards? and if not, what would the largest deck that can be used for the trick?
 A: An elegant explanation of the trick can be given easily if we work with $27=3^3$ cards, using natural numbers in base $3$.

Suppose we have shuffled the deck, and the chosen card is in position $n$, where we count starting from $0$. Write $n$ in base $3$, so that $n = abc$ with $a,b,c\in\{0,1,2\}$. We subdivide the cards in three piles, according to step (3).
You can easily verify that the card in position $xy$ of the $m$th pile is the card that originally was in position $xym$ in the deck.
Thus, our chosen card is in position $ab$ of the $c$th pile. Now we put the pile with our chosen card in the middle, according to steps (4) and (5). It is easy to see that the position of the chosen card becomes $1ab$.
Repeating this process once, we put our chosen card in position $11a$. Repeating one last time, we get it into position $111$, that is the $13$th card in the deck.

Proceeding similarly, it is easy to place the card wherever we want in the deck as final position. It is also possible to do this trick subdividing the deck in less or more than three piles each time and working with naturals in a different base, as well as using decks of different size.
