I don't understand why this card trick works

So a friend of mine showed me a very interesting card trick that I don't quite understand.

You have 52 normal cards from any regular deck you can buy anywhere. The Ace is worth 1 while 2 through 10 are worth their number value. Jack is worth 11, Queen is worth 12 and King is worth 13.

You shuffle the cards any way you want. Then you take the first card from the top of the deck and put it down on the table face up. Now, if it's a king you put it back in the deck and try again. If it's anything else you read the value on the card. Lets say you picked a 3. Now you have to put down cards from the deck in your hand on top of the 3 until you have counted 13. So 13 - 3 = 10. So you place 10 cards from the deck face up on the 3 on the table. It does not matter what the cards you place on top have in terms of values.

Now you move on to make a new set of cards on the table after the same principle. Again you cannot start on a king. If you reach a point where you can no longer put down 13 cards you keep the cards in your hand.

So I carried this out and ended up with 5 sets of cards on the table.They started with 3, 6, ace, ace and 10 leaving me with 3 cards left on my hand.

Now you take three of the decks, turn them around so they lie face down and then you pick up the rest of the cards to your hand. Now you choose 2 decks of cards and make the first card turn around so that they are face up. I have a 3 and a 10 and I have 24 cards on my hand. With 3 and 10 facing up you put that together which is 13. You have to add an extra 10 to whatever number you get so it will become 23. Now I put down 23 cards from my hand which leaves me with one card. This means that the last card currently facing down of three sets of cards on the table will be an ace.

And it was.

Why does this work?

My friend told me this could be explained or at least proven to work 100 % of the time with a mathmatical formula.


Let's skip to where all of your cards are on the table. You pick up all but three decks, and there's decks $S$, $T$, and $U$ on the table. If the top cards are $s,t,u$, then you have $(14*3 - s - t - u)$ cards on the table and $52 - (42 - s - t - u) = 10 + s + t + u$ cards in your hand. You have to put $(10 + s + t)$ cards on the table, leaving you with $(10 + s + t + u) - (10 + s + t) = u$ cards in your hand. So the number of cards you have will match the top of the turned-over deck.

Given this, here's a fun extension of the problem: why do you have to shuffle kings back in?