An Armstrong number (also known as a narcissistic number or pluperfect digital invariant) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 13+53+33=1531^3 + 5^3 + 3^3 = 15313+53+33=153. This concept can be extended to numbers with any number of digits.
This example demonstrates how to check if a given number is an Armstrong number in Java. The program includes a method to calculate the sum of the digits raised to the power of the number of digits and then compares this sum to the original number.
import java.util.Scanner;
public class ArmstrongNumberCheck {
// Method to check if a number is an Armstrong number
public static boolean isArmstrong(int number) {
int originalNumber = number;
int sum = 0;
int numberOfDigits = String.valueOf(number).length();
while (number != 0) {
int digit = number % 10;
sum += Math.pow(digit, numberOfDigits);
number /= 10;
}
return sum == originalNumber;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
scanner.close();
}
}
public class ArmstrongNumberCheck {
This line defines a new class named ArmstrongNumberCheck
. This class contains methods to check if a number is an Armstrong number and the main method to execute the program.
int originalNumber = number;
int sum = 0;
int numberOfDigits = String.valueOf(number).length();
originalNumber
stores the original number to compare later.sum
is initialized to 0 and will store the sum of the digits each raised to the power of the number of digits.numberOfDigits
calculates the number of digits in the number by converting the number to a string and getting its length.while (number != 0) {
int digit = number % 10;
sum += Math.pow(digit, numberOfDigits);
number /= 10;
}
while
loop extracts digits from the end of number
.digit
stores the last digit of the number.sum
is updated by adding the current digit raised to the power of numberOfDigits
.number
is updated by removing the last digit (integer division by 10).return sum == originalNumber;
The method returns true
if the calculated sum equals the original number, indicating it is an Armstrong number; otherwise, it returns false
.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
These lines create a Scanner
object to read input from the user and prompt the user to enter a number.
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
These lines check if the entered number is an Armstrong number using the isArmstrong
method and display the result.