Hmm. My PHP version is miniture. I just go all comment happy
Code: Select all
<?PHP
/************************************************************************
* HappyNumber.php *
* ------------------- *
* Begin: Saturday, Oct 16, 2004 *
* Copyright: (C) NeoThermic.com *
* Email: scripts@neothermic.com *
* *
************************************************************************/
/************************************************************************
* Description *
* *
* This script calculates if a number is happy or not. Happy *
* numbers are decsribed here: *
* http://mathworld.wolfram.com/HappyNumber.html *
* *
************************************************************************/
error_reporting(E_ALL ^ E_NOTICE); //cap the errors.
$computed = array();
//function IsHappy
//takes: Double input
//output: true if input is happy, false if otherwise.
function IsHappy ($input) {
//ok, to start, we need an empty array to store the already computed numbers
//(Unhappy numbers have eventually periodic sequences of Si which do not reach 1)
$runtot = 0;
global $computed;
//first, 1 is happy. Echo out true if so
if ($input == 1) {
return true;
}
//force the input to be a string so we can use the natrual string array
$input = (string)$input;
//calculate the sum of the square of the digits of the input
for ($i = 0; $i < strlen($input); $i++) {
$runtot += ($input[$i] * $input[$i]);
}
//ok, now check if result is 1
if ($runtot == 1) {
//happy!
echo " <br> Si(A) : $runtot <br>" ;
return true;
//exit;
}
//check result is not repeated
if (in_array( $runtot, $computed)) {
//if it is, its not happy
echo " <br> Si(b) : $runtot <br>" ;
return false;
exit;
} else {
//put result into an array
$computed[] = $runtot;
echo " <br> Si(c) : $runtot <br>" ;
}
//call itself with the new number
IsHappy($runtot);
}
?>
I ran into a weird return problem, which is why the echo's are labled Si(a), Si(b), and Si(c). If it ends out with an echo on line Si(a), then the number is happy, on a c, the number isn't 1 and doesn't repeate (and thus is going into the array), and if it echos out on b, then the number isn't happy.
NeoThermic