Skip to content

Commit f178b7c

Browse files
added happy number function
1 parent e21aee8 commit f178b7c

File tree

2 files changed

+31
-20
lines changed

2 files changed

+31
-20
lines changed

src/main/java/com/thealgorithms/maths/HappyNumber.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.thealgorithms.maths;
22

3+
import java.util.HashSet;
4+
35
/**
46
* A Happy Number is defined as a number which eventually reaches 1 when replaced
57
* by the sum of the squares of each digit.
@@ -54,4 +56,21 @@ private static int sumOfSquares(int num) {
5456
}
5557
return sum;
5658
}
59+
60+
/**
61+
* Checks whether the given number is a Happy Number using HashSet to detect cycles.
62+
*
63+
* @param n The number to check
64+
* @return true if n is a Happy Number, false otherwise
65+
*/
66+
public static boolean isHappyNumber(int num) {
67+
HashSet<Integer> seen = new HashSet<>();
68+
69+
while (num != 1 && !seen.contains(num)) {
70+
seen.add(num);
71+
num = sumOfSquares(num);
72+
}
73+
74+
return num == 1;
75+
}
5776
}

src/test/java/com/thealgorithms/maths/HappyNumberTest.java

Lines changed: 12 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,30 +3,22 @@
33
import static org.junit.jupiter.api.Assertions.assertFalse;
44
import static org.junit.jupiter.api.Assertions.assertTrue;
55

6-
import org.junit.jupiter.api.Test;
6+
import org.junit.jupiter.params.ParameterizedTest;
7+
import org.junit.jupiter.params.provider.CsvSource;
78

89
public class HappyNumberTest {
910

10-
@Test
11-
void testHappyNumbers() {
12-
// Known happy numbers
13-
assertTrue(HappyNumber.isHappy(1));
14-
assertTrue(HappyNumber.isHappy(7));
15-
assertTrue(HappyNumber.isHappy(19));
16-
assertTrue(HappyNumber.isHappy(100));
11+
@ParameterizedTest
12+
@CsvSource({"1", "7", "19", "100", "565", "998", "19683", "1000000"})
13+
void testHappyNumbers(final int n) {
14+
assertTrue(HappyNumber.isHappy(n));
15+
assertTrue(HappyNumber.isHappyNumber(n));
1716
}
1817

19-
@Test
20-
void testUnhappyNumbers() {
21-
// Known unhappy numbers
22-
assertFalse(HappyNumber.isHappy(2));
23-
assertFalse(HappyNumber.isHappy(4));
24-
assertFalse(HappyNumber.isHappy(20));
25-
}
26-
27-
@Test
28-
void testLargeNumber() {
29-
// Just to check behavior with larger input
30-
assertTrue(HappyNumber.isHappy(1000000)); // reduces to 1 eventually
18+
@ParameterizedTest
19+
@CsvSource({"2", "4", "20", "300", "999", "9999"})
20+
void testUnhappyNumbers(final int n) {
21+
assertFalse(HappyNumber.isHappy(n));
22+
assertFalse(HappyNumber.isHappyNumber(n));
3123
}
3224
}

0 commit comments

Comments
 (0)