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,561 questions

52,726 answers

573 users

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

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(n: number): number {
    let sum: number = 0;
    while (n > 0) {
        const d = n % 10;
        sum += d * d;
        n = Math.floor(n / 10);
    }
    return sum;
}

// Determine whether n is a happy number
function isHappy(n: number): boolean {
    const seen: Set<number> = new Set();

    while (n !== 1 && !seen.has(n)) {
        seen.add(n);
        n = sumOfDigitSquares(n);
    }
    return n === 1;
}

function main(): void {
    let a: number = 1, b: number = 100;

    if (a > b) {
        [a, b] = [b, a]; // swap
    }

    const happyNumbers: number[] = [];

    for (let i: number = a; i <= b; i++) {
        if (isHappy(i)) {
            happyNumbers.push(i);
        }
    }

    console.log(`Happy numbers in range [${a}, ${b}]:`);
    console.log(happyNumbers.join(" "));
}

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
...