loading...

re: Write a script to find "Happy Numbers" VIEW POST

FULL DISCUSSION
 

Another quick PHP one. Betting there is a more performant method but will leave that to someone else. :)

<?php

function isHappyNumber ($oldNumber) {
  $numArray = str_split($oldNumber);
  $newNumber = 0;
  foreach ($numArray as $val) {
    $newNumber += $val*$val;
  }
  if ($newNumber === 1) {
    return true;
  } else if ($newNumber === 4) {
    return false;
  } else {
    return isHappyNumber($newNumber);
  }
}



$happyNumbers = array();

for ($i = 1; $i < 100; $i++) {
  if (isHappyNumber($i)) {
    $happyNumbers[] = $i;
  }
}

print_r($happyNumbers);

?>
Code of Conduct Report abuse