×

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are only six Armstrong numbers present between 0 to 999. For example:

0 = 03 = 0

1 = 13 = 1

153 = 13 + 53 + 33 = 1 + 125 + 27 = 153

370 = 33 + 73 + 03 = 27 + 343 + 0 = 370

371 = 33 + 73 + 13 = 27 + 343 + 1 = 371

407 = 43 + 03 + 73 = 64 + 0 + 343 = 407

As we can see the given numbers are equal to the sum of cube of its digits. Hence, they are Armstrong number.

The following Java program demonstrates how to check a given number is an Armstrong number or not by using a while loop.

Iterative Approach

Filename: ArmstrongNumberExample.java

public class ArmstrongNumberExample
{             
public static void main(String[] args)
{
               int no = 407; // the number to be check if armstrong or not
               int tempVar = no; // Creating a copy of the variable no
               int sum = 0;
               while(no > 0)
               {
                               int dig = no % 10; //determining the modulo or remainder
                               sum = sum + (dig * dig * dig);//generating and adding cube of the remainder
                               no = no / 10; //removing the last digit
               }
               if(tempVar == sum)
                               System.out.print("The number " + tempVar +" is an armstrong number.");
               else
                               System.out.print("The number " + tempVar +" is not an armstrong number.");
}
}

Output:

The number 407 is an Armstrong number.

Explanation: The approach is quite straight-forward. In the first step, we assign the given number to a temporary variable named tempVar. It generates a copy of the variable no. After that, determine the remainder of the assigned no by using the modulo operator (no % 10) and the remainder store in the variable dig.

Now we find the cube of the remainder and resultant added to the variable sum. To remove the, we divide the no by 10 (no = no / 10). The same process is repeated till the given number is reduced to 0. Finally, we compare the copy of the given number with the value present in the sum variable. If the comparison between the copy (tempVar) and the sum variable yields true, then we can say the given number is an Armstrong number else not.

Let us discuss the recursive approach too.

Recursive Approach

Filename: ArmstrongNumberExample1.java

public class ArmstrongNumberExample1
{
//function to check if the number is Armstrong or no
static boolean isArmstrong(int no, int tempVar, int sum)
{
               if(no < 0)
return false;
               if(no == 0) return sum == tempVar;
               int dig = no % 10;
               return isArmstrong(no/10, tempVar, sum + (dig * dig * dig));               
}
public static void main(String[] args)
{
               int a[] = {0, 1, 7, 79, 370, 407, 797, 152};
               for(int i = 0; i < a.length; i++)
                               if(isArmstrong (a[i], a[i], 0))
                                              System.out.println("The number " + a[i] +" is an Armstrong number.");
                               else
                                              System.out.println("The number " + a[i] +" is not an Armstrong number.");
}
}

Output:

The number 0 is an Armstrong number.
The number 1 is an Armstrong number.
The number 7 is not an Armstrong number.
The number 79 is not an Armstrong number.
The number 370 is an Armstrong number.
The number 407 is an Armstrong number.
The number 797 is not an Armstrong number.
The number 152 is not an Armstrong number.

Explanation: In the recursive approach also, we are doing the same thing. Firstly, we generate a copy of the given number. Then, reducing the number to 0 by removing its last digit and adding the cube of the last digit in sum variable. Finally, making a comparison to achieve the result.

Note: A negative number never become an Armstrong number.

Armstrong Numbers Between the Two Numbers

We can also find the Armstrong number between the two given numbers. The following code illustrates the same.

Filename: ArmstrongNumberExample2.java

public class ArmstrongNumberExample2
{
//function to check if the number is Armstrong or not
static boolean isArmstrong(int no, int tempVar, int sum)
{
               if(no < 0) return false;
               if(no == 0) return sum == tempVar;
               int dig = no % 10;
               return isArmstrong(no/10, tempVar, sum + (dig * dig * dig));               
}             
public static void main(String[] args)
{
               int n1 = 0, n2 = 500 // Between n1 and n2, we will be checking Armstrong numbers.
               System.out.println("Armstrong numbers between " + n1 + " and " + n2 + " are:" );
               for(int i = n1; i <= n2; i++)
                               if(isArmstrong (i, i, 0))
                                              System.out.print(i + " ");
}

Output:

Armstrong number between 0 and 500 are:
0 1 153 370 371 407

Related Topics

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

Java Enumeration

In a computer language, enumerations express a set of named constants. For instance, the four suits in a deck of playing cards could be represented by the enumerators Club, Diamond,...

4 minutes read.

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

What is advance Java?

The definition of advance inside the dictionary refers to a forward motion, development, or progress, and the definition of enhancing is something that improves things. To become experts in that...

3 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Merge Sort in Java

Merge Sort in Java Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort. 1) Divide the...

5 minutes read.