Friday, February 14, 2014

Java program to check if number is Armstrong or not.


/**
* @file : ArmstrongExample.java
* @description :
*/

/**
A number is called as ARMSTRONG number if,sum of cube of every digit present in the number is equal
to the number itself then that number is called as armstrong number.For example the 153 is a armstrong
number because 1^3 + 5^3 + 3^3 =153. 
 
Some of the Armstrong number are 0, 1, 153, 370, 371, 407
 
*/

package com.ranga.collections;

import java.util.Scanner;

/**
* Java program to check if number is Armstrong or not.
* @author: ranga
* @date: Feb 13, 2014
*/
public class ArmstrongExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Number: ");
int num = scanner.nextInt();
boolean isArmstrong = isArmstrong(num);
if(isArmstrong) {
System.out.println(num +" is Armstrong");
} else {
System.out.println(num +" not Armstrong");
}
}
private static boolean isArmstrong(int num) {
int number = num;
int sum = 0;
do {
int den = num % 10;
sum = den * den * den + sum;
num = num / 10;
} while(num != 0);

if(number == sum) {
return true;
}
return false;
}
} 
 
Output: 
Enter Number: 
141
141 not Armstrong

Enter Number: 
153
153 is Armstrong


Explanation:
Assume Number is 153
 
Step1: 
 
Initially
number = 153
sum = 0

after entering while loop

den = 153 % 10 = 3
sum = 3 * 3 * 3 + 0(sum) = 27
num = 153 / 10 = 15
 
next do while check the do while condition i.e num != 0 = 15 != 0 = true

Step2:

Now sum = 27
    num = 15
 
den = 15 % 10 = 5
sum = 5 * 5 * 5 + 27(sum) = 125 + 27 = 152
num = 15 / 10 = 1
 
next it will check condition i.e num != 0 = 1 != 0 = true
 
Step3:
 
Now sum = 152
    num = 1
 den = 1 % 10 = 1
 sum = 1 * 1 * 1 + 152(sum) = 1 + 152 = 153
 num = 1 / 10 = 0
next it will check do while condition i.e num != 0 = 0 != 0 = false
 
Now program exits the while loop...
 
then we are comparing the number == sum i.e 153 == 153
 
 
 

0 comments: