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

1 Answer

0 votes
import java.util.HashSet;
import java.util.ArrayList;

// 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 number

public class HappyNumbers {

    // Compute the sum of squares of digits of n
    static 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
    static boolean isHappy(int n) {
        HashSet<Integer> seen = new HashSet<>();

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

    public static void main(String[] args) {
        int a = 1, b = 100;

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

        ArrayList<Integer> happyNumbers = new ArrayList<>();

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

        System.out.println("Happy numbers in range [" + a + ", " + b + "]:");
        for (int n : happyNumbers) {
            System.out.print(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
...