I am trying out a code that finds out whether a number entered is Armstrong or not. Here is the Code:
import java.util.*;
public class Arm {
int a, b, c;
void m1() {
Scanner obj = new Scanner(System.in);
System.out.println("Enter a number");
int number = obj.nextInt();
number = (100 * a) + (10 * b) + (1 * c);
if ((a * a * a) + (b * b * b) + (c * c * c) == number) {
System.out.println("number is armstrong");
} else {
System.out.println("number is not armstrong");
}
}
public static void main(String args[]) {
Arm obj = new Arm();
obj.m1();
}
}
Here the value of a,b and c comes out to be zero. But that is not the correct result. Say if we enter a number 345
. Then a
,b
and c
should be 3, 4 and 5 respectively.
Please guide.
That is not how you calculate a, b, c.
To find a,b,c we repeatedly divide by 10
and get the remainder by modulus
.
int digit = 0;
int sum = 0;
while(num > 0)
{
digit = num % 10;
sum += Math.pow(digit, 3);
num = num/10;
}
Why do we use /
and %
Consider 345
.
Now to get the last digit what can be done?
What does a modulus return? The remainder, so If we perform %10
we get the last digit.
345 % 10 = 5
Now we want the second last digit.
So we divide the number by 10, so we get the quotient
345 / 10 = 34
Now again if we can perform the modulus we get the 4
and so on..
What does 100 * a + 10 * b + 1 * c do?
That is used to get a number if we have the individual digits.
Suppose we have 3, 4, 5 we know that we get 345
out of it but how do we do it?
3 * 100 = 300
4 * 10 = 40
5 * 1 = 5
-----------
300 + 40 + 5 = 345
Now to complete your whole program.
public boolean isAmg(int num)
{
int digit = 0;
int sum = 0;
int copyNum = num; //used to check at the last
while(num > 0)
{
digit = num % 10;
sum += Math.pow(digit, 3);
num = num / 10;
}
return sum == copyNum;
}