In this post, we are going to write a program to check armstrong number in java.
Given a number x, write a code to check whether a number x is Armstrong Number or not. Let’s first understand what is Armstrong number?
Armstrong number
An Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits.
For example – 153, 371 is an Armstrong number.
Example 1: 153 has 3 digits.
153 : 13 + 53 + 33 = 153
Example 2 – Take an example of 6 which has 1 digit.
6: 61 = 6 It’s an Armstrong number
Example 3 – Take another example let’s say 15, it has 2 digits.
15 : 12 + 52 = 26
So 15 is not an Armstrong number.
Example 4 – This time let’s take bigger number 1634, it has 4 digits.
1634 : 14 + 64 + 34 + 44 = 1634
So, we can say 1634 is a 4 digit armstrong number.
How to Check Armstrong Number in Java
We know that, An Armstrong number is a number that is equal to the sum of the nth power of it’s digits.
Here are the following steps –
i) First step is to count number of digits present in a number.
ii) Once we know the number of digits present in a number. Then we can calculate the sum of nth power of it’s digits.
iii) Once the sum is calculated, Compare the original number to the calculated sum. If both are equal then it’s an Armstrong number else it’s not.
Program to Check Armstrong Number in Java
We have discussed the logic to check whether an input number is Armstrong or not. Let’s write a java code to implement this logic.
Armstrong number in java video tutorial
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
/** * Armstrong Number Program in Java */ public class ArmstrongNumber { /** *Count number of digits of a number */ private static int countNoOfDigits(int num) { int len = 0; while(num > 0) { num = num/10; len++; } return len; } public static boolean isArmStrong(int num) { int temp = num; int sum = 0; int len = countNoOfDigits(num); while(temp > 0) { int digit = temp % 10; sum = (int) (sum + Math.pow(digit, len)); temp = temp/10; } if(sum == num) { return true; } return false; } public static void main(String[] args) { int num = 153; boolean armstrong = isArmStrong(num); if(armstrong) { System.out.println("Armstrong number"); } else { System.out.println(" Not an armstrong number"); } } } |
More Programming Questions
Java program to find first non-repeated character of a string