An Armstrong number (also known as a narcissistic number) is an integer that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because (1^3 + 5^3 + 3^3 = 153). Developing a Java program to find all Armstrong numbers between two given intervals can be an excellent exercise to enhance your understanding of loops, conditionals, and mathematical operations in Java.
In this article, you will learn how to create a Java program that efficiently identifies and displays all Armstrong numbers within a specified range. Explore how to implement the logic using methods and loops, handle user input, and optimize the process for better performance.
Create a method named isArmstrong
that takes an integer as its parameter.
Compute the sum of the cubes of its digits and check if it matches the original number.
public static boolean isArmstrong(int number) {
int originalNumber, remainder, result = 0, n = 0;
originalNumber = number;
for (;originalNumber != 0; originalNumber /= 10, ++n);
originalNumber = number;
for (;originalNumber != 0; originalNumber /= 10) {
remainder = originalNumber % 10;
result += Math.pow(remainder, n);
}
return result == number;
}
This method first calculates the number of digits in the number (n
). It then uses these digits, elevating each to the power n
and accumulating the results. Finally, it returns true
if the sum is equal to the original number, indicating it's an Armstrong number.
Implement user input processing to determine the range.
Use a loop to iterate through all numbers in this range and utilize the isArmstrong
method to check each number.
import java.util.Scanner;
public class ArmstrongRange {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int low, high;
System.out.print("Enter the lower bound: ");
low = scanner.nextInt();
System.out.print("Enter the upper bound: ");
high = scanner.nextInt();
System.out.printf("Armstrong numbers between %d and %d are: ", low, high);
for (int number = low; number <= high; number++) {
if (isArmstrong(number)) {
System.out.print(number + " ");
}
}
scanner.close();
}
}
In this main
method, the program prompts the user to enter the lower and upper bounds of the range. It then checks each number within the specified range to see if it's an Armstrong number using the isArmstrong
method defined earlier. If it is, the program prints the number.
The ability to find Armstrong numbers between two intervals in Java not only enhances your grasp of basic concepts such as loops and conditionals but also improves your mathematical problem-solving skills in programming. This program, which combines user input processing and method implementation, showcases the practical application of Java in solving mathematical problems. Test and expand this program further by modifying it to handle larger numbers and different types of intervals, thus deepening your understanding of Java programming.