Reputation: 5
So I'm trying to find every Armstrong number between 1-500. I have to only use a For Loop for this, I know people can also use While loops. I'm not sure what im doing wrong here. Its only giving me 375, but I know numbers like 153 is also an armstrong number. `
Here my code :
public class ArmstrongNumber {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Armstrong numbers 1-500
int D1;
int D2;
int D3;
for (int number = 1; number <= 500 ; number++) {
int temp=number;
D1=number%10; //ones
temp= temp/10;
D2=number%10; //tens
temp= temp/10;
D3=number%10; //hundreds
if( ((D1*D1*D1) + (D2*D2*D2) + (D3*D3*D3)) == number)
{
System.out.println(number + " is a Armstrong number");
}
}
}
}
Upvotes: 0
Views: 145
Reputation: 40062
Armstrong numbers are numbers where the sum of the digits, each raised to the power of the number of digits in that number equals the number. Your method above will miss some numbers because you are not considering the number of digit of all numbers.
So the digits 1 thru 9 are each Armstrong numbers since each raised to the power of 1 is that number.
Here is one way to check for all numbers up to a certain point.
// the digits raised to the power of 1
int[] powers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int nextPower = 10;
for (int r = 1; r <= 500; r++) {
int n = r;
int sum = 0;
while (n > 0) {
// sum of the powers
sum += powers[n % 10];
// if at any time the sum exceeds the number
// break out of the loop
if (sum > r) {
break;
}
n /= 10;
}
if (sum == r) {
System.out.println(r + " is an Armstrong number.");
}
// check to see if time to transition to next power.
if (r == nextPower - 1) {
nextPower *= 10;
// and increase each digits power
for (int i = 2; i < powers.length; i++) {
powers[i] *= i;
}
}
}
Prints
1 is an Armstrong number.
2 is an Armstrong number.
3 is an Armstrong number.
4 is an Armstrong number.
5 is an Armstrong number.
6 is an Armstrong number.
7 is an Armstrong number.
8 is an Armstrong number.
9 is an Armstrong number.
153 is an Armstrong number.
370 is an Armstrong number.
371 is an Armstrong number.
407 is an Armstrong number.
Upvotes: 0
Reputation: 4491
You have to use remainder operation (%
) to tmp
:
for (int number = 1; number <= 500; number++) {
int temp = number;
D1 = temp % 10; //ones
temp = temp / 10;
D2 = temp % 10; //tens
temp = temp / 10;
D3 = temp % 10; //hundreds
if (((D1 * D1 * D1) + (D2 * D2 * D2) + (D3 * D3 * D3)) == number) {
System.out.println(number + " is a Armstrong number");
}
}
)))
Upvotes: 0
Reputation: 7109
You should write D2 = temp%10 and D3 = temp%10 (temp instead of number).
Upvotes: 1