Open In App

Java Program to Check Armstrong Number between Two Integers

Improve
Improve
Like Article
Like
Save
Share
Report

A positive integer with digits p, q, r, s…, is known as an Armstrong number of order n if the following condition is fulfilled.

pqrs... = pn + qn + rn + sn +....

Example:

370 = 3*3*3 + 7*7*7 + 0 
   =  27 + 343 + 0
   =  370

Therefore, 370 is an Armstrong number.

Examples:

Input : 100 200
Output :153
Explanation : 100 and 200 are given  
two integers.
 153 = 1*1*1 + 5*5*5 + 3*3*3  
     = 1 + 125 + 27
     =  153
Therefore, only 153 is an Armstrong number between 100 and 200.

Approach:

Firstly, we will traverse through all the numbers in the given range. Then, for every number, we have to count the number of digits in it. If the number of digits in the current number is n then, find the sum of (n-th) power of all the digits in the number stated. And if the sum is equal to the current number i, then print the number.

Example:

Java




// JAVA program to find Armstrong
// numbers between two integers
import java.io.*;
import java.math.*;
  
class gfg {
  
    // Function to print Armstrong
    // Numbers between two integers
    static void ArmstrongNum(int l, int h)
    {
        for (int j = l + 1; j < h; ++j) {
  
            // Calculating number of digits
            int y = j;
            int N = 0;
            while (y != 0) {
                y /= 10;
                ++N;
            }
  
            // Calculating the sum of nth
            // power of all the digits
            int sum_power = 0;
            y = j;
            while (y != 0) {
                int d = y % 10;
                sum_power += Math.pow(d, N);
                y /= 10;
            }
  
            // Checking if the current number
            // i is equal to the sum of nth
            // power of all the digits
            if (sum_power == j)
                System.out.print(j + " ");
        }
    }
  
    // The Driver code
    public static void main(String args[])
    {
        int n1 = 50;
        int n2 = 500;
        ArmstrongNum(n1, n2);
        System.out.println();
    }
}


Output

153 370 371 407 

Similarly, we can find Armstrong numbers within any given range.



Last Updated : 17 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads