Write a program to print out all Armstrong numbers between a range of numbers entered by user. The following is a sample of output:
Sample 1
enter the range of numbers :10 100
the Armstrong numbers are:
No Armstrong Numbers found:
sample 2
enter the range of numbers : 100 2000
the Armstrong Numbers are :
153
370
371
407
1634
import java.util.Scanner;
public class ArmstrongNumbers {
private static int power(int number, long e) {
if (e == 0) {
return 1;
}
if (e % 2 == 0) {
return power(number, e / 2) * power(number, e / 2);
}
return number * power(number, e / 2) * power(number, e / 2);
}
private static int calculateOrderNumber(int number) {
int counter = 0;
while (number != 0) {
counter++;
number = number / 10;
}
return counter;
}
private static boolean isArmstrong(int number) {
int n = calculateOrderNumber(number);
int tempNumber = number, sum = 0;
while (tempNumber != 0) {
int r = tempNumber % 10;
sum = sum + power(r, n);
tempNumber = tempNumber / 10;
}
return (sum == number);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("enter the range of numbers: ");
int startnumber = input.nextInt();
int endnumber = input.nextInt();
System.out.println("the Armstrong numbers are:");
int counter = 0;
for (int number = startnumber; number <= endnumber; number++) {
if (isArmstrong(number)) {
System.out.println(number);
counter++;
}
}
if (counter == 0) {
System.out.println("No Armstrong Numbers found:");
}
input.close();
}
}
Comments
Leave a comment