Friday 22 May 2015

Program: Armstrong Number in Java

If sum of each digits's cube is equal to original number then that number is called as Armstrong Number

Example: 153 = (1*1*1) + (5*5*5) + (3*3*3)


Please follow below Steps to check if number is armstrong number or not using java :

i.   Take Reminder of number
ii.  Cube the reminder and add it to Sum
iii. Retrieve pending number to be evaluate and set it to Number
iv.  Perform above checks until number is greater than 0.


// Example: 153 = (1*1*1) + (5*5*5) + (3*3*3)
package in.blogspot.java2bigdata;  
  
/** 
 * 
 * @author Mahendhar E 
 */  
public class ArmStrong {  
  
    protected void checkArmStrongNumber(int number) {  
        int sum = 0, reminder = 0;  
        int original = number;  
  
        while (number > 0) {  
            //take reminder  
            reminder = number % 10;  
  
            //cube the reminder and add it to sum  
            sum = sum + reminder * reminder * reminder;  
  
            //retrieve pending number to be eveluated  
            number = number / 10;  
        }  
  
        if (original == sum) {  
            System.out.println("Number " + original + " is armstrong");  
        } else {  
            System.out.println("Number " + original + " is not armstrong");  
        }  
    }  
  
    public static void main(String[] args) {  
        ArmStrong armStrong = new ArmStrong();  
        armStrong.checkArmStrongNumber(153);  
        armStrong.checkArmStrongNumber(154);  
    }  
}


output:
/**
 *
 * Number 153 is armstrong  
 * Number 154 is not armstrong 
 */

No comments:

Post a Comment