File tree Expand file tree Collapse file tree
main/java/com/thealgorithms/maths
test/java/com/thealgorithms/maths Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .thealgorithms .maths ;
2+
3+ /**
4+ * Disarium number is a number where the sum of its digits powered
5+ * with their respective positions is equal to the number itself.
6+ * Example: 135 = 1^1 + 3^2 + 5^3 = 1 + 9 + 125 = 135
7+ *
8+ * @see <a href="https://en.wikipedia.org/wiki/Disarium_number">Disarium Number</a>
9+ */
10+ public final class DisariumNumber {
11+
12+ private DisariumNumber () {
13+ }
14+
15+ /**
16+ * Checks if a number is a Disarium number.
17+ *
18+ * @param number the number to check (must be positive)
19+ * @return true if number is Disarium, false otherwise
20+ * @throws IllegalArgumentException if number is not positive
21+ */
22+ public static boolean isDisarium (int number ) {
23+ if (number <= 0 ) {
24+ throw new IllegalArgumentException ("Input must be a positive integer." );
25+ }
26+ int digits = String .valueOf (number ).length ();
27+ int temp = number ;
28+ int sum = 0 ;
29+ while (temp > 0 ) {
30+ int lastDigit = temp % 10 ;
31+ sum += (int ) Math .pow (lastDigit , digits );
32+ digits --;
33+ temp /= 10 ;
34+ }
35+ return sum == number ;
36+ }
37+ }
Original file line number Diff line number Diff line change 1+ package com .thealgorithms .maths ;
2+
3+ import static org .junit .jupiter .api .Assertions .assertFalse ;
4+ import static org .junit .jupiter .api .Assertions .assertThrows ;
5+ import static org .junit .jupiter .api .Assertions .assertTrue ;
6+
7+ import org .junit .jupiter .api .Test ;
8+
9+ class DisariumNumberTest {
10+
11+ @ Test
12+ void testDisariumNumbers () {
13+ assertTrue (DisariumNumber .isDisarium (1 ));
14+ assertTrue (DisariumNumber .isDisarium (89 ));
15+ assertTrue (DisariumNumber .isDisarium (135 ));
16+ assertTrue (DisariumNumber .isDisarium (175 ));
17+ assertTrue (DisariumNumber .isDisarium (518 ));
18+ }
19+
20+ @ Test
21+ void testNonDisariumNumbers () {
22+ assertFalse (DisariumNumber .isDisarium (10 ));
23+ assertFalse (DisariumNumber .isDisarium (100 ));
24+ assertFalse (DisariumNumber .isDisarium (200 ));
25+ }
26+
27+ @ Test
28+ void testInvalidInput () {
29+ assertThrows (IllegalArgumentException .class , () -> DisariumNumber .isDisarium (0 ));
30+ assertThrows (IllegalArgumentException .class , () -> DisariumNumber .isDisarium (-5 ));
31+ }
32+ }
You can’t perform that action at this time.
0 commit comments