×

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

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.