Table of Contents

**Introduction**

The program below demonstrates how to check for Armstrong numbers between two integers in Java.

**What are Armstrong Numbers?**

A positive number with digits a, b, c, d, … n is called an Armstrong number of the order of n if the number meets the condition laid out below:

abcd …… n = a^n + b^n + c^n + …. n^n

**Example:**

153 can be written as 1^3 + 5^3 + 3^3 which is equal to 1 + 125 + 7 = 153.

Therefore 153 is an Armstrong number.

**Some more Examples are as follows:**

Input: 100 410

Output: 153 370 371 407

Explanation: 10 and 400 are given two integers (which is the interval).

For 153, if we calculate the cube of each digit as 1^3 + 5^3 + 3^3, which is equal to 1 + 125 + 7 and which results into 153.

For 370 , if we calculate the cube of each digit as 3^3 + 7^3 + 0^3, which is equal to 27 + 343 + 0 and which results into 370.

For 371 , if we calculate the cube of each digit as 3^3 + 7^3 + 1^3, which is equal to 27 + 343 + 1 and which results into 371.

For 407, if we calculate the cube of each digit as 4^3 + 0^3 + 7^3, which is equal to 64 + 0 + 343 and which results into 407.

**Approach:**

The approach for this program is quite simple. We will have to traverse through all the numbers that will be taken up by the loop control variable. For every number, first, the number of digits in that number will be counted. The number of digits will then be assigned to the variable n. We will then have to compute the nth power of every digit. According to the example above, if the sum of the nth power of all the digits is equal to the number itself, we will return ‘the number is an Armstrong number’.

**Sample Code**

import java.io.*; import java.math.*; class Demo { static void findArstrong (int low, int high) { for (int I = low + 1; I < high; I ++) { int x = I; int n = 0; while (x ! = 0) { x/= 10; ++n; } //compute sum of the nth power of the digits int pow_sum = 0; x = I; while (x ! = 0) { int digit = x % 10; pow_sum += Math.pow (digit, n); x/= 10; } //check if the number I is equal to the sum of the nth power of the digit if (pow_sum == i) { System.out.println ( I + “ ” ); } } public static void main (String args []) { int num1 = 100; int num2 = 400; findArmstrong (num1, num2); System.out.println (); } }

**OUTPUT:**

153 370 371

## 0 Comments