A strange little number - $6174$. Take a 4 digit number such that it isn't made out the same digit $(1111, 2222, .. . $ etc$)$ Define an operation on such a four digit number by taking the largest number that can be constructed out of these digits and subtracting the smallest four digit number. For example, given the number $2341$, we have, 
$4321 - 1234 = 3087$
Repeating this process with the results (by allowing leading zeroes) we get the following numbers:
$8730 - 0378 = 8352$
$8532 - 2358 = 6174$
What's more interesting is that with $6174$ we get
$7641 - 1467 = 6174$
and taking any four digit number we end up with 6174 after at most 7 iterations. A bit of snooping around the internet told me that this number is called the Kaprekar's constant. A three digit Kaprekar's contant is the number 495 and there's no such constant for two digit numbers.
My question is, how can we go about proving the above properties algebraically? Specifically, starting with any four digit number we arrive at 6174. I know we can simply test all four digit numbers but the reason I ask is, does there exist a 5 digit Kaprekar's constant? Or an $n$-digit Kaprekar's constant for a given $n$?
 A: Here I have a partial solution for your question. With some additional simple calculations you can obtain a complete algebraic solution. I would like to start with two and three digit numbers. It will help you to understand my solution.

*

*Take a two digit number $ab=10a+b.$ Without loss of generality assume that $a>b.$ Then $$ab-ba=9(a-b)$$ Repeated use of your algorithm on this number goes to the cycle of multiples of $9$ between $9$ and $90.$


*Take a three digit number $abc$ and with out loss of generality assume that $a \ge b \ge c$ and $a\not= c.$ Then suppose $$abc-cba=99(a-c)=ABC$$ Note that $A\not=9, \,\,\ B=(b-1)+10-b=9$ and $ABC$ can  be divide by $9$ and $11$ respectively. Hence $A+C=9.$ Therefore $ABC$ should be one of the number in the set $$\{198, 297, 396, 495, 594, 693, 792, 891\}$$ Repeted using your algorithm on any of this number will end up at the $495.$


*Take a four digit number $abcd$ and as in the previous steps without loss of generality assume that $a\ge b\ge c\ge d$ and $a\not= d.$ Also suppose $$abcd-dcba=999(a-d)+90(b-c)=ABCD.$$ Note that $$A\not=9\\ D=10-a+d \\ C=(c-1)+10-b=9-b+c$$
If $b=c$ then $$B=(b-1)+10-c=9+b-c\\ A=-1+a-d.$$ This implies $B+C=18,\,\ A+C=9.$
Therefore $B=C=9$ and $(A,C)\in\{(0,9),(1,8),(2,7),(3,6),(4,5),(5,4),(6,3),(7,2).(8,1),(9,0)\}$
If $b>c$ then $$B=-1+b-c\\ A=a-d.$$ This implies $B+C=8,\,\ A+C=10.$
Therefore $(B,C)\in \{(0,8),(1,7), ...,(8,0)$ and $(A,C)\in\{(1,9),(2,8), ...,(9,1)\}$
Here you have $91$ possible values for $ABCD.$ I think you can continue from here. Apply your algorithm on all of them. If your $abcd$ of the form $a=b=c$ or $b=c=d,$ then you will end up with $0.$ Otherwise you will end up with $6174.$
