Number is called as ArmStrong number if sum of each digits's cube is equal to original number.
Ex. 153 = (1*1*1) + (5*5*5) + (3*3*3)
Please follow below Steps to check if number is armstring number or not using java :
1. Take Reminder of number
2. Cube the reminder and add it to Sum
3. Retrieve pending number to be evaluate and set it to Number
4. Perform above checks until number is greater than 0.
Java Program to check number is armstrong number or not :
Output :
Number 153 is armstrong
Number 154 is not armstrong
Ex. 153 = (1*1*1) + (5*5*5) + (3*3*3)
Please follow below Steps to check if number is armstring number or not using java :
1. Take Reminder of number
2. Cube the reminder and add it to Sum
3. Retrieve pending number to be evaluate and set it to Number
4. Perform above checks until number is greater than 0.
Java Program to check number is armstrong number or not :
package com.anuj.algorithms; /** * * @author Anuj Patel */ public class ArmStrong { protected void checkIsArmStrongNumber(int num) { int sum = 0, reminder = 0; int original = num; while (num > 0) { //take reminder reminder = num % 10; //cube the reminder and add it to sum sum = sum + reminder * reminder * reminder; //retrieve pending number to be eveluated num = num / 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.checkIsArmStrongNumber(153); armStrong.checkIsArmStrongNumber(154); } }
Output :
Number 153 is armstrong
Number 154 is not armstrong
No comments:
Post a Comment