Skip to content

Commit 6ecb0a3

Browse files
Add Armstrong Number algorithm with comprehensive tests
- Implemented ArmstrongNumber.isArmstrong() method - Added comprehensive unit tests for Armstrong numbers - Includes documentation with examples - Handles edge cases (negative numbers, zero) - Tests cover known Armstrong numbers: 0, 1, 153, 370, 371, 407, 1634 Signed-off-by: duvvuvenkataramana <[email protected]>
1 parent f693c44 commit 6ecb0a3

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.thealgorithms.maths;
2+
3+
/**
4+
* Armstrong Number (also known as Narcissistic Number)
5+
* A number is called an Armstrong number if the sum of cubes of its digits equals the number itself.
6+
* For example: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
7+
*
8+
* @author duvvuvenkataramana
9+
*/
10+
public final class ArmstrongNumber {
11+
private ArmstrongNumber() {
12+
}
13+
14+
/**
15+
* Check if a number is an Armstrong number
16+
*
17+
* @param number the number to check
18+
* @return true if the number is an Armstrong number, false otherwise
19+
*/
20+
public static boolean isArmstrong(int number) {
21+
if (number < 0) {
22+
return false;
23+
}
24+
25+
int original = number;
26+
int sum = 0;
27+
int digits = String.valueOf(number).length();
28+
29+
while (number > 0) {
30+
int digit = number % 10;
31+
sum += Math.pow(digit, digits);
32+
number /= 10;
33+
}
34+
35+
return sum == original;
36+
}
37+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
6+
import org.junit.jupiter.api.Test;
7+
8+
class ArmstrongNumberTest {
9+
10+
@Test
11+
void testArmstrongNumbers() {
12+
// Test known Armstrong numbers
13+
assertTrue(ArmstrongNumber.isArmstrong(0));
14+
assertTrue(ArmstrongNumber.isArmstrong(1));
15+
assertTrue(ArmstrongNumber.isArmstrong(153));
16+
assertTrue(ArmstrongNumber.isArmstrong(370));
17+
assertTrue(ArmstrongNumber.isArmstrong(371));
18+
assertTrue(ArmstrongNumber.isArmstrong(407));
19+
assertTrue(ArmstrongNumber.isArmstrong(1634));
20+
}
21+
22+
@Test
23+
void testNonArmstrongNumbers() {
24+
// Test numbers that are not Armstrong numbers
25+
assertFalse(ArmstrongNumber.isArmstrong(10));
26+
assertFalse(ArmstrongNumber.isArmstrong(100));
27+
assertFalse(ArmstrongNumber.isArmstrong(152));
28+
assertFalse(ArmstrongNumber.isArmstrong(200));
29+
}
30+
31+
@Test
32+
void testNegativeNumbers() {
33+
// Negative numbers cannot be Armstrong numbers
34+
assertFalse(ArmstrongNumber.isArmstrong(-1));
35+
assertFalse(ArmstrongNumber.isArmstrong(-153));
36+
}
37+
}

0 commit comments

Comments
 (0)