An Armstrong number (also called a Narcissistic number) 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, a 3-digit Armstrong number is a number for which the sum of the cubes of its digits is equal to the number itself. Similarly, a 4-digit Armstrong number is a number where the sum of the fourth powers of its digits is equal to the number.
For the number 153:
1^3 + 5^3 + 3^3 = 1 +125 + 27 = 153
Since the sum (153) is equal to the original number, 153 is an Armstrong number.
import java.util.Scanner;
public class ArmstrongNumber {
// Function to check if a number is an Armstrong number
public static boolean isArmstrong(int num) {
int originalNum = num; // Store the original number
int sum = 0;
int n = 0;
// Step 1: Count the number of digits in the number
while (num != 0) {
num /= 10;
n++;
}
num = originalNum; // Reset num to its original value
// Step 2: Calculate the sum of digits raised to the power of n
while (num != 0) {
int digit = num % 10; // Extract the last digit
sum += Math.pow(digit, n); // Raise it to the power of n and add to sum
num /= 10; // Remove the last digit
}
// Step 3: Check if sum is equal to the original number
return sum == originalNum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 4: Ask the user to input a number
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Step 5: Check if the number is an Armstrong number
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
scanner.close();
}
}
isArmstrong(int num)
:
originalNum
) to compare later.sum
to 0, which will store the sum of each digit raised to the power of the number of digits (n
).Count the number of digits (n
):
while
loop to count how many digits are in the number.num /= 10
removes the last digit from num
by integer division.Calculate the sum of each digit raised to the power of n
:
num % 10
(this gives the remainder when divided by 10, i.e., the last digit).n
using Math.pow(digit, n)
.Math.pow
function returns a double, but since we’re working with integers, this value is automatically converted to an integer during summation.num
using integer division (num /= 10
).Compare the sum with the original number:
true
, indicating it’s an Armstrong number; otherwise, it returns false
.main
method:
isArmstrong
method to check if the input number is an Armstrong number.Single-digit numbers (1 to 9):
1
, 2
, 3
, …, 9
are all Armstrong numbers.Large numbers:
Negative numbers: