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.
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; exit("kaprekar not found, probably a number with 3 digits the same"); } } echo "</table>"; echo "Kaprekar in {$j} iterations \n";
- floatingworks's blog
- Log in to post comments
Example random number. Reload for a new number.
desc | asc | ||
---|---|---|---|
6067 | 7660 | 0667 | 7660-0667=6993 |
6993 | 9963 | 3699 | 9963-3699=6264 |
6264 | 6642 | 2466 | 6642-2466=4176 |
4176 | 7641 | 1467 | 7641-1467=6174 |