English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to use Java functions to display all Armstrong numbers between two given intervals (low and high)
To find all Armstrong numbers between two integers, the function checkArmstrong() will be created. This functionCheck if the number is an Armstrong number.
public class Armstrong { public static void main(String[] args) { int low = 999, high = 99999; for(int number = low + 1; number < high; ++number) { if (checkArmstrong(number)) System.out.print(number + " "); } } public static boolean checkArmstrong(int num) { int digits = 0; int result = 0; int originalNumber = num; //Digit Calculation while (originalNumber != 0) { originalNumber /= 10; ++digits; } originalNumber = num; //The result contains the sum of the n-th powers of its digits while (originalNumber != 0) { int remainder = originalNumber % 10; result += Math.pow(remainder, digits); originalNumber /= 10; } if (result == num) return true; return false; } }
When running the program, the output is:
1634 8208 9474 54748 92727 93084
In the above program, we created a function named checkArmstrong() that takes a parameter num and returns a boolean value.
If the number is an Armstrong number, return true. If not, return false.
Print output numbers on the main() function based on the return value.