no % 10
.
no = no / 10
.
public class CheckArmstrongNumber
{
public static void main(String[] args)
{
int no = 153;
int originalNumber = no;
int sum = 0;
// Calculate the number of digits
int temp = no;
int digits = 0;
while (temp != 0)
{
digits++;
temp = temp / 10;
}
while (no != 0)
{
int rem = no % 10;
int mul = 1;
// Calculate rem^digits using a basic loop
for (int i = 0; i < digits; i++)
{
mul = mul * rem;
}
sum = sum + mul;
no = no / 10;
}
if (sum == originalNumber)
{
System.out.println(originalNumber + " is an Armstrong number.");
}
else
{
System.out.println(originalNumber + " is not an Armstrong number.");
}
}
}
153 is an Armstrong number.
import java.util.Scanner;
public class CheckArmstrongNumber
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int no = scanner.nextInt();
int originalNumber = no;
int sum = 0;
// Calculate the number of digits
int temp = no;
int digits = 0;
while (temp != 0)
{
digits++;
temp = temp / 10;
}
while (no != 0)
{
int rem = no % 10;
int mul = 1;
// Calculate rem^digits using a basic loop
for (int i = 0; i < digits; i++)
{
mul = mul * rem;
}
sum = sum + mul;
no = no / 10;
}
if (sum == originalNumber)
{
System.out.println(originalNumber + " is an Armstrong number.");
}
else
{
System.out.println(originalNumber + " is not an Armstrong number.");
}
}
}
Enter a number: 1634 1634 is an Armstrong number.
Scanner
and store it in an integer variable no
. no = 1634
sum
to 0 to keep track of the sum of the multiplication digits. int sum = 0;
while
loop:
temp
to avoid modifying the original number.
digits
counter until the number becomes 0. 1634
, the number of digits is 4.
no % 10
. 1634
, the last digit is 4
.
for
loop
digits
times. sum = 0 + 256 = 256
1634
becomes 163
.
256 + 81 + 1296 + 1 = 1634
.
sum
with the original number (originalNumber
)
System.out.println()
.
scanner.close()
to avoid resource leaks.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.