-
Notifications
You must be signed in to change notification settings - Fork 19.7k
/
Copy pathHappyNumbersSeq.java
39 lines (33 loc) · 993 Bytes
/
HappyNumbersSeq.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.thealgorithms.others;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public final class HappyNumbersSeq {
private HappyNumbersSeq() {
}
private static final Set<Integer> CYCLE_NUMS = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145));
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int n = in.nextInt();
while (n != 1 && !isSad(n)) {
System.out.print(n + " ");
n = sumSquares(n);
}
String res = n == 1 ? "1 Happy number" : "Sad number";
System.out.println(res);
in.close();
}
private static int sumSquares(int n) {
int s = 0;
for (; n > 0; n /= 10) {
int r = n % 10;
s += r * r;
}
return s;
}
private static boolean isSad(int n) {
return CYCLE_NUMS.contains(n);
}
}