1. Overview
In this tutorial, you'll learn how to check the given number is armstrong or not.
This is a commonly asked interview questions for freshers to check the basic logical skill and programming skills.
This is easy to understand if you know the following simple concepts in java.
A positive integer is called an Armstrong number of order n if
abcd... = an + bn + cn + dn + ...
In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number itself. For example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.
2. Example - Check Number Armstrong
public class ArmstrongNumberExample {
public static void main(String[] args) {
// storing the input number
int number = 153;
// original number
int originalNumber = number;
// cubic sum of each digit
double sumCubic = 0;
// getting cubic sum of each digit and adding to sumCubic varaible
while (number > 0) {
int digit = number % 10;
sumCubic = sumCubic + Math.pow(digit, 3);
number = number / 10;
}
// comparing the original value and result sumCubic
if(originalNumber == sumCubic) {
System.out.println(originalNumber+" number is armstrong");
} else {
System.out.println(originalNumber+" number is not armstrong");
}
}
}
153 number is armstrong
3. Example - Check Number Armstrong for Order n
public class ArmstrongNumberOrderNExample {
public static void main(String[] args) {
// storing the input number
int number = 1634;
// original number
int originalNumber = number;
// cubic sum of each digit
double sumCubic = 0;
// finding the length of number
int length = 0;
while (number > 0) {
number = number / 10;
length++;
}
// getting cubic sum of each digit and adding to sumCubic varaible
while (number > 0) {
int digit = number % 10;
sumCubic = sumCubic + Math.pow(digit, length);
number = number / 10;
}
// comparing the original value and result sumCubic
if (originalNumber == sumCubic) {
System.out.println(originalNumber + " number is armstrong");
} else {
System.out.println(originalNumber + " number is not armstrong");
}
}
}
1634 number is not armstrong

No comments:
Post a Comment
Please do not add any spam links in the comments section.