Armstrong number
A number is said to be an armstrong number if the sum of cubes of each digit is equal to the number itself.
For Example:
Let's take 125 : (1*1*1)+(2*2*2)+(5*5*5)
: 1+8+125=134(which is not equal to 125) , so 125 is not armstrong number.
if number is 371:(3*3*3)+(7*7*7)+(1*1*1)
:27+343+1=371 (so, it's an armstrong number)
now we know what is armstrong number the remaining part is to write a program to check. How do we do that? how do we check each digit? ...
The approach is simple we take each digit and find cube of that number and add.
For example the number is 125
- first we need 5 (if we divide 125 by 10 we get 5 as remainder)--so we do modulo division which gives remainder .(125%10) to get 5
- So step 1: i=125%10 ; and find i*i*i which can be done by using Math.pow or simply doing (i*i*i).
- Now, we got five, next we need 2. so we do we divide 125 by 10 which is 12( 125/10=12) and we take that result and again do modulo division on 12 (12%10=2).
- We repeat this number until all the digits are over.
Java Implementation
public class armstrong{ public static void main(String args[]){ int n=153; int rem=0,sum=0; int temp=n; while(n!=0){ rem=n%10; sum=sum+(int)Math.pow(rem,3); n=n/10; } if(sum==temp){ System.out.println("Armstrong number"); } else{ System.out.println("Not armstrong number"); } } }
Output:
Armstrong number
you can also use scanner to make user enter the value to check.
to do that include these lines in place of "int n=153;"
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
Comments
Post a Comment