Print Armstrong Numbers Between Two Integers in Java

Mathematics and programming when combined make a very deadly combination. As the ability to solve complex mathematical questions in itself is a great deal. But when one has to do the same thing by writing up a code, things get somewhat more complicated. Not to mention the language your coding in also determines whether it’s going to be easy to difficult. Well, Armstrong numbers are very well known in the mathematical world. Therefore today we’re going to write a program to print Armstrong Numbers Between Two Integers in Java.

 

What are Armstrong Numbers?

 

  • Let us consider Number X with N being the no digits in X. Then X will be said as the Armstrong number if the sum of each digit of X is raised with order N equals to X itself.

 

  • Eg:  153 is the Armstrong Number.
  • Therefore, 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3 = 153

 

Also Read: How to Install Java JDK JRE on Windows 11

 

What’s The Approach?

 

  • We’ll iterate a for loop where Low and High will determine the range of integers we’ll have to traverse.

 

  • For each integer in the range, we will Find The Number Of Digits (N) so that we can determine the order.

 

  • Once we find the order, then for each digit (R) we will compute  RN After that, we will perform the addition of the computed values.

 

  • If the computed addition equals iterative variable i of the for loop we’ll print it, otherwise, we’ll pass.

 

Java Program To Print Armstrong Numbers Between Two Integers

 

Input:

num1 = 100
num2 = 400
Output:

153 370 371

 

// JAVA program to find Armstrong
// numbers in between two integers
import java.io.*;
import java.math.*;

class TechDecodeTutorials {
    
    // Prints Armstrong Numbers in given range
    static void findArmstrong(int low, int high)
    {
        for (int i = low + 1; i < high; ++i) {
    
            // number of digits calculation
            int x = i;
            int n = 0;
            while (x != 0) {
                x /= 10;
                ++n;
            }
    
            // compute sum of nth power of
            // its digits
            int pow_sum = 0;
            x = i;
            while (x != 0) {
                int digit = x % 10;
                pow_sum += Math.pow(digit, n);
                x /= 10;
            }
    
            // checks if number i is equal
            // to the sum of nth power of
            // its digits
            if (pow_sum == i)
                System.out.print(i + " ");	
        }
    }
    
    // Driver code
    public static void main(String args[])
    {
        int num1 = 100;
        int num2 = 400;
        findArmstrong(num1, num2);
        System.out.println();
    }
}


 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *