How to find all happy numbers in a specific range with PHP

1 Answer

0 votes
// A happy number is a number that eventually reaches 1 
// when repeatedly replaced by the sum of the squares of its digits.
//
// 19 = 1^2 + 9^2 = 82
// 19 -> 82 -> 68 ->100 -> 1 eventually reaches 1 
// 19 = happy numbe

// Compute the sum of squares of digits of n
function sumOfDigitSquares(int $n): int {
    $sum = 0;
    while ($n > 0) {
        $d = $n % 10;
        $sum += $d * $d;
        $n = intdiv($n, 10);
    }
    return $sum;
}

// Determine whether n is a happy number
function isHappy(int $n): bool {
    $seen = [];

    while ($n !== 1 && !isset($seen[$n])) {
        $seen[$n] = true;
        $n = sumOfDigitSquares($n);
    }
    return $n === 1;
}

function main() {
    $a = 1;
    $b = 100;

    if ($a > $b) {
        $temp = $a;
        $a = $b;
        $b = $temp;
    }

    $happyNumbers = [];

    for ($i = $a; $i <= $b; $i++) {
        if (isHappy($i)) {
            $happyNumbers[] = $i;
        }
    }

    echo "Happy numbers in range [$a, $b]:\n";
    foreach ($happyNumbers as $n) {
        echo $n . " ";
    }
    echo "\n";
}

main();


/*
run:

Happy numbers in range [1, 100]:
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 

*/

 



answered Feb 24 by avibootz
edited Feb 24 by avibootz
...