Write a Java program to check whether a given number is an Armstrong number or not.
This program checks whether a given number is an Armstrong number (also known as a Narcissistic number or Pluperfect number). 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.
What Does the Program Do?
The program checks if a number is an Armstrong number. For example:
- Input: 153
- Calculation:
- Number of digits = 3
- 13+53+33=1531^3 + 5^3 + 3^3 = 15313+53+33=153
- Since the sum of powers of the digits equals the original number,
153
is an Armstrong number.
- Output: Armstrong
class Main {
public static void main(String[] args) {
int userNo = 153; // The number to check
int originalUserNo = userNo; // Store the original number for comparison
int result = 0; // To store the sum of the powers of the digits
int digits = 0; // To store the number of digits
int temp = userNo; // A temporary variable for calculation
// Calculate the number of digits in userNo
while (userNo != 0) {
userNo /= 10; // Divide by 10 to remove the last digit
digits++; // Increase the digit count
}
userNo = originalUserNo; // Reset userNo back to the original number
// Calculate the sum of the digits raised to the power of the number of digits
while (userNo != 0) {
int digit = userNo % 10; // Extract the last digit
result += Math.pow(digit, digits); // Add digit raised to the power of digits
userNo /= 10; // Remove the last digit
}
// Check if the result equals the original number
if (result == originalUserNo) {
System.out.print("Armstrong");
} else {
System.out.print("Not Armstrong");
}
}
}
Armstrong
Input Initialization:
userNo = 153: The number to check.
originalUserNo = userNo: Store the original number to compare later.
result = 0: Variable to store the sum of the digits raised to the power of the number of digits.
digits = 0: Variable to store the number of digits in the number.
temp = userNo: A temporary variable used for digit extraction.
Calculate the Number of Digits:
The first while loop counts the number of digits in userNo.
It repeatedly divides userNo by 10 and increments digits.
After the loop, digits holds the count of digits in the number.
Calculate the Sum of Digits Raised to the Power:
The second while loop processes each digit of userNo.
userNo % 10 extracts the last digit.
Math.pow(digit, digits) raises the extracted digit to the power of digits and adds it to result.
userNo /= 10 removes the last digit from userNo until it becomes 0.
Check for Armstrong Number:
After calculating the sum of the digits raised to the power of digits, the program compares the result with originalUserNo.
If they are equal, the number is an Armstrong number, and the program prints “Armstrong”.
Otherwise, it prints “Not Armstrong”.