Skip to content

fix: handle zero case in Armstrong number check to avoid Math.log10(0… #6229

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 17 additions & 12 deletions src/main/java/com/thealgorithms/maths/Armstrong.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,24 @@ public class Armstrong {
* @return {@code true} if the given number is an Armstrong number, {@code false} otherwise
*/
public boolean isArmstrong(int number) {
if (number < 0) {
return false; // Negative numbers cannot be Armstrong numbers
}
long sum = 0;
int totalDigits = (int) Math.log10(number) + 1; // get the length of the number (number of digits)
long originalNumber = number;
if (number < 0) {
return false; // Negative numbers cannot be Armstrong numbers
}
if (number == 0) {
return true; // 0 is an Armstrong number
}

while (originalNumber > 0) {
long digit = originalNumber % 10;
sum += (long) Math.pow(digit, totalDigits); // The digit raised to the power of total number of digits and added to the sum.
originalNumber /= 10;
}
long sum = 0;
int totalDigits = (int) Math.log10(number) + 1;
long originalNumber = number;

return sum == number;
while (originalNumber > 0) {
long digit = originalNumber % 10;
sum += (long) Math.pow(digit, totalDigits);
originalNumber /= 10;
}

return sum == number;
}

}
Comment on lines +24 to 44
Copy link
Collaborator

@DenizAltunkapan DenizAltunkapan Apr 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very thoughtful of you! Nice that you noticed. Please run Clang to format your code, as the pipeline is failing — the rest looks good to me! 😊 @Tejaswi1305