This is just a bullshit post, not practical at all, but math is good shit and I decided to make this for fun in 30 minutes… If you are unfamiliar with Kaprekar’s Constant.. well the breakdown is as follows..
Take any four digit number (whose digits are not all identical), and follow the steps:
Tip:If there is a 0, 5032 for example its not 532-235, its 5320 – 0235.
DEMO:
<h1>Kaprekar's Constant</h1> <h2>Directions:</h2> <p>Enter a 4-digit number that are not all the same digits and watch Kaprekar's Constant turn into 6174.</p> <form method="POST" > <input type="text" size="30" name="number" /> <input type="submit" value="Calculate" /> </form>
//Check if the number is there and Trim whitespace
if (isset($_POST['number'])) {
$number = trim($_POST['number']);
//Run the function
kaprekars($number);
}
function kaprekars($number) {
//Not set? Let them know.
if ((empty($number)) && (isset($number))) {
$errors[] = 'Make sure you enter something.';
}
//Not numeric? Let them know.
if (!is_numeric($number)) {
$errors[] = 'Make sure its a number.';
}
//Not 4 digits? Let them know.
if ((strlen($number) < 4) || (strlen($number) > 4)) {
$errors[] = 'Make sure its 4 digits.';
}
//If its 4 digits it cant be 1111 or 8888, let them know.
//Define the arrays, because if you loop and its empty.. the variable doesnt get set, just an error
$forwards = array();
$backwards = array();
//loopz
for ($i=0; $i<strlen($number); $i++) {
//Make an array of the numbers
$forwards[$i] = substr($number,$i, 1);
}
//Reverse it
$backwards = array_reverse($forwards);
//Comepare...are they the same? YES, fucking error bitch.
if ($forwards == $backwards) {
$errors[] = 'The value must not be four of the same digit.';
}
//Errors array set?
if (isset($errors)) {
//YES, so loop through and output them.
echo '<ul id="errors">';
foreach ($errors as $k => $v) {
echo '<li class="errors_text">' . $v . '</li>';
}
echo '</li>';
die();
} else {
//make sure the number is not 6174
while ($number != "6174") {
//IF its 3 digits like 333 append a 0 in front of it
if (strlen($number) == 3) {
$number = '0' . $number;
}
//loop through the length of the sum which is always 4
for ($i=0; $i<strlen($number); $i++) {
//Create an array called combined based on $i which is 0 to 3 aka 4 by 1
// e.g. $combined = array(6,1,7,4);
$combined[$i] = substr($number,$i, 1);
}
//sort the array ascending 1467
sort($combined);
$asc = implode("",$combined);
//now descending 7641<br>
rsort($combined);
$desc = implode("",$combined);
//subtract it to get the next number until you hit Kaprekars constant 6174
$number = $desc - $asc;
//Output it.
echo $desc . ' - ' . $asc . ' = ' . $number . '<br />';
}
}
}