Skip to content

Commit 63a08ba

Browse files
Added HappyNumber algorithm in maths section
1 parent 5e9d9f7 commit 63a08ba

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package com.thealgorithms.maths;
2+
3+
/**
4+
* A Happy Number is defined as a number which eventually reaches 1 when replaced
5+
* by the sum of the squares of each digit.
6+
* If it falls into a cycle that does not include 1, then it is not a happy number.
7+
*
8+
* Example:
9+
* 19 → 1² + 9² = 82
10+
* 82 → 8² + 2² = 68
11+
* 68 → 6² + 8² = 100
12+
* 100 → 1² + 0² + 0² = 1 → Happy Number!
13+
*/
14+
public final class HappyNumber {
15+
16+
private HappyNumber() {
17+
}
18+
19+
/**
20+
* Checks whether the given number is a Happy Number.
21+
* Uses Floyd’s Cycle Detection algorithm (tortoise and hare method)
22+
* to detect loops efficiently.
23+
*
24+
* @param n The number to check
25+
* @return true if n is a Happy Number, false otherwise
26+
*/
27+
public static boolean isHappy(int n) {
28+
int slow = n;
29+
int fast = n;
30+
31+
do {
32+
slow = sumOfSquares(slow); // move 1 step
33+
fast = sumOfSquares(sumOfSquares(fast)); // move 2 steps
34+
} while (slow != fast);
35+
36+
return slow == 1; // If cycle ends in 1 → Happy number
37+
}
38+
39+
/**
40+
* Calculates the sum of squares of the digits of a number.
41+
*
42+
* Example:
43+
* num = 82 → 8² + 2² = 64 + 4 = 68
44+
*
45+
* @param num The number to calculate sum of squares of digits
46+
* @return The sum of squares of the digits
47+
*/
48+
private static int sumOfSquares(int num) {
49+
int sum = 0;
50+
while (num > 0) {
51+
int digit = num % 10;
52+
sum += digit * digit;
53+
num /= 10;
54+
}
55+
return sum;
56+
}
57+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.thealgorithms.maths;
2+
3+
import static org.junit.jupiter.api.Assertions.assertFalse;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
5+
import org.junit.jupiter.api.Test;
6+
7+
public class HappyNumberTest {
8+
9+
@Test
10+
void testHappyNumbers() {
11+
// Known happy numbers
12+
assertTrue(HappyNumber.isHappy(1));
13+
assertTrue(HappyNumber.isHappy(7));
14+
assertTrue(HappyNumber.isHappy(19));
15+
assertTrue(HappyNumber.isHappy(100));
16+
}
17+
18+
@Test
19+
void testUnhappyNumbers() {
20+
// Known unhappy numbers
21+
assertFalse(HappyNumber.isHappy(2));
22+
assertFalse(HappyNumber.isHappy(4));
23+
assertFalse(HappyNumber.isHappy(20));
24+
}
25+
26+
@Test
27+
void testLargeNumber() {
28+
// Just to check behavior with larger input
29+
assertTrue(HappyNumber.isHappy(1000000)); // reduces to 1 eventually
30+
}
31+
}

0 commit comments

Comments
 (0)