diff --git a/src/main/java/com/thealgorithms/maths/Armstrong.java b/src/main/java/com/thealgorithms/maths/Armstrong.java index dda8288a..526b31c3 100644 --- a/src/main/java/com/thealgorithms/maths/Armstrong.java +++ b/src/main/java/com/thealgorithms/maths/Armstrong.java @@ -1,29 +1,36 @@ package com.thealgorithms.maths; /** - * An Armstrong number is equal to the sum of the cubes of its digits. For - * example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. An - * Armstrong number is often called Narcissistic number. + * This class checks whether a given number is an Armstrong number or not. + * An Armstrong number is a number that is equal to the sum of its own digits, + * each raised to the power of the number of digits. * - * @author Vivek + * For example, 370 is an Armstrong number because 3^3 + 7^3 + 0^3 = 370. + * 1634 is an Armstrong number because 1^4 + 6^4 + 3^4 + 4^4 = 1634. + * An Armstrong number is often called a Narcissistic number. + * + * @author satyabarghav */ public class Armstrong { /** - * Checks whether a given number is an armstrong number or not. + * Checks whether a given number is an Armstrong number or not. * - * @param number number to check - * @return {@code true} if given number is armstrong number, {@code false} - * otherwise + * @param number the number to check + * @return {@code true} if the given number is an Armstrong number, {@code false} otherwise */ public boolean isArmstrong(int number) { long sum = 0; - long number2 = number; - while (number2 > 0) { - long mod = number2 % 10; - sum += Math.pow(mod, 3); - number2 /= 10; + String temp = Integer.toString(number); // Convert the given number to a string + int power = temp.length(); // Extract the length of the number (number of digits) + long originalNumber = number; + + while (originalNumber > 0) { + long digit = originalNumber % 10; + sum += Math.pow(digit, power); // The digit raised to the power of the number of digits and added to the sum. + originalNumber /= 10; } + return sum == number; } } diff --git a/src/test/java/com/thealgorithms/maths/ArmstrongTest.java b/src/test/java/com/thealgorithms/maths/ArmstrongTest.java index 3b11b83d..e5d0d9eb 100644 --- a/src/test/java/com/thealgorithms/maths/ArmstrongTest.java +++ b/src/test/java/com/thealgorithms/maths/ArmstrongTest.java @@ -5,8 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; /** - * @author Vivek - * @since 15/03/22 + * @author satyabarghav + * @since 4/10/2023 */ class ArmstrongTest { @@ -17,7 +17,9 @@ class ArmstrongTest { assertThat(armstrong.isArmstrong(1)).isTrue(); assertThat(armstrong.isArmstrong(153)).isTrue(); assertThat(armstrong.isArmstrong(371)).isTrue(); - assertThat(armstrong.isArmstrong(1634)).isFalse(); + assertThat(armstrong.isArmstrong(1634)).isTrue(); assertThat(armstrong.isArmstrong(200)).isFalse(); + assertThat(armstrong.isArmstrong(548834)).isTrue(); + assertThat(armstrong.isArmstrong(9474)).isTrue(); } }