Java Program to Display Armstrong Number Between Two Intervals

In this program, you’ll learn to display all armstrong numbers between two given intervals, low and high, 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.

This program is built on the concept of how to check whether an integer is an Armstrong number or not.

Example: Armstrong Numbers Between Two Integers

  1. public class Armstrong {
  2. public static void main(String[] args) {
  3. int low = 999, high = 99999;
  4. for(int number = low + 1; number < high; ++number) {
  5. int digits = 0;
  6. int result = 0;
  7. int originalNumber = number;
  8. // number of digits calculation
  9. while (originalNumber != 0) {
  10. originalNumber /= 10;
  11. ++digits;
  12. }
  13. originalNumber = number;
  14. // result contains sum of nth power of its digits
  15. while (originalNumber != 0) {
  16. int remainder = originalNumber % 10;
  17. result += Math.pow(remainder, digits);
  18. originalNumber /= 10;
  19. }
  20. if (result == number)
  21. System.out.print(number + " ");
  22. }
  23. }
  24. }

When you run the program, the output will be:

1634 8208 9474 54748 92727 93084 

In the above program, each number between the given interval high and low are checked.

After each check, number of digits and sum result are restored to 0.