Java program to find the amstrong numbers between interval has been shown here. A positive integer of order n is called an amstrong number if the sum of each digit to the power n is equal to that number. For example, 8 and 370 are amstrong numbers as $8 = 8^1$ and $370 = 3^3 + 7^3 + 0^3$.
The amstrong numbers between 1 and 400 are 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371.
The algorithm, pseudocode and time complexity of the program have been shown below.
1. Algorithm to find amstrong numbers between interval
1. Take lower limit l and upper limit u as inputs.
2. For each number n between l and u
3. Calculate d, the total no of digit of n
4. Extract each digit $p_i$ and perform sum = $\sum_{i=1}^d p_i ^d$
5. Check If sum = n
6. If step 5 is true, then display n as an amstrong number
7. Go to step 2 to check next number
2. Pseudocode to find amstrong numbers between interval
Input : Lower bound $l$ and Upper bound $u$
Output : Amstrong numbers between $l$ and $u$
1. Procedure findAmstrong($l, u$):
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12. End Procedure
3. Time complexity to find amstrong numbers between interval
Time Complexity: O(nlog(k))
Where n is the total no. of integers between lower and upper bound and k is the average length of the integers.
4. Java Program & output to find amstrong numbers between interval
/****************************** alphabetacoder.com Java program to find amstrong numbers between interval *******************************/ import java.util.Scanner; import java.lang.Math; class Main { public static void main(String args[]) { // declare instance of Scanner class Scanner sc = new Scanner(System.in); // declare variables int u, l, n, d = 0, t, r, sum = 0; // take input of lower and upper bound System.out.print("Enter the lower bound = "); l = sc.nextInt(); System.out.print("Enter the upper bound = "); u = sc.nextInt(); System.out.print("Amstrong numbers between " + l + " and " + u + ": "); // check each number from l to u for (n = l; n <= u; n++) { // initialize t = n; d = 0; sum = 0; // calculate the number of digit while (t != 0) { d++; t = t / 10; } // copy value t = n; // find the sum of digits each to the power d while (t != 0) { r = t % 10; sum = sum + (int) Math.pow(r, d); t = t / 10; } //check if input number is amstrong or not if (n == sum) System.out.print(n + " "); } } }
Output
Enter the lower bound = 100
Enter the upper bound = 100000
Amstrong numbers between 100 and 10000: 153 370 371 407 1634 8208 9474