How to find all happy numbers in a specific range with C++

1 Answer

0 votes
#include <iostream>
#include <unordered_set>
#include <vector>

// 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
int sumOfDigitSquares(int n) {
    int sum = 0;
    while (n > 0) {
        int d = n % 10;
        sum += d * d;
        n /= 10;
    }
    return sum;
}

// Determine whether n is a happy number
bool isHappy(int n) {
    std::unordered_set<int> seen;

    while (n != 1 && !seen.count(n)) {
        seen.insert(n);
        n = sumOfDigitSquares(n);
    }
    return n == 1;
}

int main() {
    int a = 1, b = 100;

    if (a > b) std::swap(a, b);

    std::vector<int> happyNumbers;

    for (int i = a; i <= b; ++i) {
        if (isHappy(i)) {
            happyNumbers.push_back(i);
        }
    }

    std::cout << "Happy numbers in range [" << a << ", " << b << "]:\n";
    for (int n : happyNumbers) {
        std::cout << n << " ";
    }
}



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