Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,087 questions

52,056 answers

573 users

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 2 days ago by avibootz
edited 2 days ago by avibootz
...