Armstrong numbers between two intervals using Java

Armstrong numbers between two intervals using java :

In this article we will create a java program to find all armstrong numbers between two intervals. For this purpose we will ask the user to enter starting range and ending range so that all armstrong numbers between this range can be find and an armstrong number of three digits is the number whose sum of the cubes of its digits is equal to the given number or can say the number itself should be the result.

Let us consider an example for understanding armstrong number in a better way.

Example :

  • Suppose a number is 407 ;
  • Cubes of its digits are :

Cube of 4 = 64 ;

Cube of 0 = 0 ;

Cube of 7 =  343 ;

  • Sum of all digit’s cube : 64 + 0 + 343 =407

Here the calculated result is equal to the given number ;

So, 407 is an Armstrong Number. 

Armstrong numbers between two intervals using Java

Working :

Step 1 : Ask the user to enter two ranges , one starting range and second ending range.

Step 2 : Use  a loop to find all armstrong numbers between starting range and ending range.

Step 3 : Use the logic for checking number is armstrong or not for every number between the given range and then display the result. 

Code in Java :

//Java program to print armstrong numbers between two intervals
import java.util.Scanner;
public class armstrong_numbers_between_two_intervals
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter Starting Number : ");
int start = sc.nextInt();
System.out.print("Enter Ending Number : ");
int end = sc.nextInt();
System.out.println("Armstrong numbers between "+start+" and "+end+" are : ");
int n, sum;
//loop for finding and printing all prime numbers between given range
for(int i = start ; i <= end ; i++)
{
n = i;
sum = 0;
//logic for checking number is armstrong or not
while(n != 0)
{
int pick_last = n % 10;
sum = sum + (pick_last * pick_last * pick_last);
n = n / 10;
}
if(sum == i)
System.out.println(i);
}
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter Starting Number : 10
Enter Ending Number : 1000
Armstrong numbers between 10 and 1000 are :
153
370
371
407

Please Login/Signup to comment