How to print all the happy numbers between 1 and N in Java

1 Answer

0 votes
// 8^2 + 2^2 = 68
// 6^2 + 8^2 = 100
// 1^2 + 0^2 + 0^2 = 1 = happy number

public class Program
{
	private static int isHappyNumber(int num) {
		int sum = 0;

		while (num > 0) {
			int reminder = num % 10;
			sum = sum + (reminder * reminder);
			num = num / 10;
		}

		return sum;
	}

	public static void main(String[] args)
	{
		int N = 100;

		for (int i = 1; i <= N; i++) {
			int num = i;
			int result = num;
			
			while (result != 1 && result != 4) {
				result = isHappyNumber(result);
			}

			if (result == 1) {
				System.out.print(num + " ");
			}
		}
	}
}




/*
run:
 
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 
 
*/

 



answered Nov 16, 2022 by avibootz

Related questions

...