# Kaprekar's Constant - 6174

6174 looks pretty straightforward but try this.
Sort it by highest to lowest digit : 7641
Reverse the resulting number : 1467
Subtracting 1467 from 7641 leaves 6174

We get to Kaprekar's constant. 6174. That whole iteration is called Kaprekar's routine and any 4 digit number that has at least 2 different digits will reach 6174 in at most 7 iterations. Which this script replicates.

Kaprekars constant

```function kapsort(\$random, \$highToLow = false){

\$count =strlen(\$random);
\$sorted = '';
\$arrParts = array();

for (\$i=0; \$i<\$count; \$i++){
\$parts[\$i] = \$random[\$i];
}

if(\$highToLow){
arsort(\$parts);
} else {
asort(\$parts);
}

foreach(\$parts as \$val){
\$sorted .= \$val;
}

return \$sorted;

}

\$n = (string)rand(1000,9999);

echo "<table>";
echo "<caption>Candidate : {\$n}</caption>";
echo "<tr><th></th><th>Descending</th><th>Ascending</th><th></th>";
\$j=0;
while (\$n != 6174) {
\$sortedHigh2Low = kapsort((string)\$n, true);
\$sortedLow2High = kapsort((string)\$n, false);
echo "<tr>";
echo "<td width=\"100\">\$n</td><td width=\"100\">".\$sortedHigh2Low."</td>";
echo "<td width=\"100\">".\$sortedLow2High."</td>";
\$n = \$sortedHigh2Low - \$sortedLow2High;
echo "<td>{\$sortedHigh2Low}-{\$sortedLow2High}=\$n</td></tr>";
\$j++;
if(\$j>=8) {
\$j=0;
}
}
echo "</table>";

echo "Kaprekar in {\$j} iterations \n";

```

## Example random number. Reload for a new number.

Candidate : 1839
descasc
1839983113899831-1389=8442
8442844224488442-2448=5994
5994995445999954-4599=5355
5355555335555553-3555=1998
1998998118999981-1899=8082
8082882002888820-0288=8532
8532853223588532-2358=6174
Kaprekar in 7 iterations