Java Program to print Armstrong number from 100 to 500
Objective
Write a Java program to find and print all Armstrong numbers between 100 and 500.
Algorithm / Approach
- Start a
forloop withirunning from 100 to 500. - Inside the loop, assign
ito a temporary variabletemp. - Initialize
sumto 0. - Use a
whileloop to extract digits fromtempuntil it becomes 0. - Extract the last digit using
r = temp % 10. - Cube the digit (
r * r * r) and add it tosum. - Remove the last digit from
tempusingtemp = temp / 10. - After the while loop, if
sum == i, print the numberi.
Test.java
class Test {
public static void main(String[] a)
{
int temp,r,sum;
for(int i=100; i<=500; i++) {
temp = i;
sum = 0;
while(temp!=0) {
r = temp%10;
sum = sum+(r*r*r);
temp = temp/10;
}
if(sum ==i) {
System.out.print(i+" ");
}
}
}
}
Expected Output
153 370 371 407
Explanation of the Program
- An Armstrong number of 3 digits is an integer such that the sum of the cubes of its digits is equal to the number itself.
- The outer loop iterates through the target range (100 to 500).
- The inner while loop processes each digit of the current number mathematically without converting it to a string.
- Because we need the original number for the final comparison, we perform the digit extraction on a copy (
temp) rather than modifyingidirectly.
Complexity
Time Complexity
O(N * log10(M)) - Where N is the range size (400) and M is the maximum value (500).
Space Complexity
O(1)
Common Mistakes
- Modifying the loop variable
idirectly in the while loop, causing an infinite loop becauseidrops to 0. - Forgetting to reset
sum = 0at the start of each iteration in the outer loop.