Armstrong Number in Java using Different Methods

# Armstrong Number in Java using Different Methods

7 mins read5.5K Views 1 Comment
Atul Harsha
Senior Manager Content
Updated on Oct 25, 2023 10:56 IST

Learn to check if a number is an Armstrong number in Java using while loop or recursion. Understand the mathematical definition and see code examples for easy implementation

An Armstrong number, also known as a narcissistic number, is a number that is equal to the sum of its own digits each raised to the power of the number of digits. In this article, we will learn how to check if a number is an Armstrong number using Java.

For example,

153 is an Armstrong number because 13 + 53 + 33 =1 + 125 + 27 = 153.

## Implementing Armstrong Number in Java using different methods

### Armstrong Number in JAVA Using For Loop:

• The “is_armstrong(n)” function checks if a given number, “n”, is an Armstrong number.
• The function converts the number to a string to access its individual digits.
• It counts the number of digits in the number by getting the length of the string.
• A variable called “armstrong_sum” is used to store the sum of each digit raised to the power of the number of digits.
• The function iterates through each digit in the number, where in each iteration,
• the digit is converted to an integer
• raised to the power of the number of digits
• added to the “armstrong_sum” variable.
• The function compares the original number to the “armstrong_sum”.
• If the two are equal, the number is an Armstrong number and the function returns True, or else False.
` `
`public boolean isArmstrong(int n) { // Step 1: Convert the number to a string to access its individual digits String numStr = Integer.toString(n); // Step 2: Get the number of digits in the number int numDigits = numStr.length(); // Step 3: Initialize a variable to store the sum of the digits raised to the power of the number of digits int armstrongSum = 0; // Step 4: Iterate over each digit in the number for (int i = 0; i < numDigits; i++) { // Step 4a: Convert the digit from a string to an integer int digit = Integer.parseInt(Character.toString(numStr.charAt(i))); // Step 4b: Raise the digit to the power of the number of digits and add it to the armstrongSum armstrongSum += Math.pow(digit, numDigits); } // Step 5: Compare the original number to the armstrongSum if (armstrongSum == n) { return true; } else { return false; }}Copy code`
Armstrong Number in C
An Armstrong Number is defined as the sum of the nth power of each digit to an n-digit number that is equal to that number. Confused! Don’t worry. In this...read more
How to Find an Armstrong Number Using Python
Learn how to find Armstrong numbers using Python with our step-by-step guide. Discover the algorithm to identify these special numbers, which are equal to the sum of their own digits...read more
How to Find Reverse of a Number in Java
Reversing a number in Java is a common task that can be accomplished using a variety of methods. For example, you can use a loop to iterate over the digits...read more
Check Palindrome in Java Using Different Methods
Discover various methods for checking if a string is a palindrome in Java. Use recursion and string manipulation to efficiently determine if a string is a palindrome, ignoring spaces, punctuation,...read more
Fibonacci Series in Java [Case-Study Based]
The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. In Java, the Fibonacci...read more

### Armstrong Number in JAVAUsing While Loop:

• The method takes in an integer as a parameter
• It initializes a variable temp to the value of the input number, num, in order to keep the original value of num unmodified
• The length variable is used to store the number of digits in the input number
• Using a while loop, the method:
• Obtains the last digit of the number by taking the remainder of temp divided by 10
• Cubes the last digit and adds it to the sum variable
• Removes the last digit from the number by dividing temp by 10
• After the loop, the method checks if the sum of cubes of the digits is equal to the original input number
• If they are equal, it returns true, indicating that the input number is an Armstrong number else it returns false
` `
```// This method checks whether the input number is an Armstrong number or not using a while loop public boolean isArmstrongNumberUsingWhile(int num) { // Initialize a variable temp to the value of input num int temp = num; int sum = 0; // find the length of the input number int length = String.valueOf(num).length(); //Loop until temp is greater than 0 while (temp > 0) { // Obtain the last digit int lastDigit = temp % 10; // add the cube of the last digit to sum sum += Math.pow(lastDigit, length); // remove the last digit temp /= 10; } // Check if the sum of cubes of digits is equal to the original number return sum == num;}Copy code```

### Armstrong Number in JAVAUsing Recursion:

• Method to check if an input number is an Armstrong number using recursion
• Takes in 3 integers: input number, length of the input number, and a sum variable
• Uses recursion to calculate the sum of the cubes of digits
• Base case is when input number is 0, returns comparison of sum and input number
• Recursive case: obtains last digit, cubes it and adds to sum, calls itself with updated number, length, and sum
• Returns final value of the last recursive call
` `
`public boolean isArmstrongNumberUsingRecursion(int num, int length, int sum) { //base case: if the input number is 0 if (num == 0) { // check if the sum of cubes of digits is equal to the original number return sum == num; } else { //recursive case: //obtain the last digit int lastDigit = num % 10; // add the cube of the last digit to sum sum += Math.pow(lastDigit, length); //call the function recursively with updated num (removing last digit) length, and sum return isArmstrongNumberUsingRecursion(num / 10, length, sum); }}Copy code`
Swapping of Two Numbers in Java
Get an introduction to swapping the values of two numbers in Java using different methods. Compare the use of a temporary variable, arithmetic operators, and bitwise operators for swapping numbers.
How to Check Leap Year in Java?
In this blog, you will learn how to check leap year in Java. A leap year is a year that is divisible by 4 and 400 but not by 100....read more
Switch Case in Java with Examples
Switch statements in Java enable execution of different code blocks based on the value of an expression. They provide an alternative to multiple if-else statements and can be used when...read more

## Real life Use case of Armstrong number in Java

### Unlocking the Secrets: Exploration of Armstrong Numbers in Cryptography using Java

Armstrong numbers have potential use in cryptography as a one-way function for encrypting a message.

The idea is to convert each character in the plaintext message to its corresponding ASCII value. Raise each ASCII value to the power of the number of characters in the message and concatenate the resulting values to form the encrypted message, and use it as the encryption key.

Problem Statement: Implement a program in Java that can encrypt and decrypt a plaintext message using the property of Armstrong numbers (narcissistic numbers). The program should have the following functions:

Encryption:

1. Take a plaintext message as input from the user.
2. Convert each character in the plaintext message to its corresponding ASCII value.
3. Raise each ASCII value to the power of the number of characters in the message.
4. Concatenate the resulting values to form the encrypted message.
5. Output the encrypted message to the user.

Decryption:

1. Take an encrypted message as input from the user.
2. Iterate through each digit of the encrypted message.
3. Raise each digit to the power of the number of digits in the encrypted message.
4. Sum the values of each digit raised to the power.
5. Check if the sum of the values is equal to the original input, if yes, it’s an armstrong number.
6. Add the corresponding ASCII character to the decrypted message.
7. Output the decrypted message to the user.

## Solution:

` `
```import java.math.BigInteger;import java.util.Scanner; public class ArmstrongEncryption { public static void main(String[] args) { // Initialize scanner to read input from the user Scanner input = new Scanner(System.in); // Prompt user for plaintext message to encrypt System.out.println("Enter a plaintext message to encrypt: "); String plaintext = input.nextLine(); // Encrypt the plaintext message String encryptedMessage = encrypt(plaintext); System.out.println("Encrypted message: " + encryptedMessage); // Prompt user for encrypted message to decrypt System.out.println("Enter an encrypted message to decrypt: "); String encrypted = input.nextLine(); // Decrypt the encrypted message String decryptedMessage = decrypt(encrypted); System.out.println("Decrypted message: " + decryptedMessage); } // Method to encrypt a plaintext message public static String encrypt(String plaintext) { // Initialize empty string to store the encrypted message String encryptedMessage = ""; // Get the number of characters in the plaintext message int n = plaintext.length(); // Iterate through each character in the plaintext message for (int i = 0; i < plaintext.length(); i++) { // Convert the character to its ASCII value int asciiValue = (int) plaintext.charAt(i); // Raise the ASCII value to the power of n BigInteger asciiValueRaised = BigInteger.valueOf(asciiValue).pow(n); // Add the resulting value to the encrypted message string encryptedMessage += asciiValueRaised; } // Return the encrypted message return encryptedMessage; } // Method to decrypt an encrypted message public static String decrypt(String encrypted) { // Initialize empty string to store the decrypted message String decryptedMessage = ""; // Get the number of digits in the encrypted message int n = String.valueOf(encrypted).length(); // Iterate through each digit in the encrypted message for (int i = 0; i < encrypted.length(); i++) { // Get the current digit char digit = encrypted.charAt(i); // Raise the digit to the power of n int digitRaised = (int) Math.pow(Character.getNumericValue(digit), n); // Add the resulting value to a sum int sum = 0; sum += digitRaised; // Check if the sum is equal to the original input if (sum == Integer.parseInt(encrypted)) { // if yes, it's an armstrong number // add the corresponding ASCII character to the decrypted message decryptedMessage += (char) (sum); } else { // otherwise, it's not an armstrong number System.out.println("Encrypted message is not an Armstrong number.\n Decryption failed."); return null; } } // Return the decrypted message return decryptedMessage; }}Copy code```

The process of encrypting a plaintext message using the property of Armstrong numbers involves the following steps:

1. Converting each character in the plaintext message to its corresponding ASCII value.
2. Raising each ASCII value to the power of the number of characters in the message.
3. Concatenating the resulting values to form the encrypted message.

This method essentially utilizes the property of Armstrong numbers, where the sum of each digit raised to the power of the number of digits is equal to the original number, to encrypt the message.

On the other hand, the process of decrypting the message involves:

1. Iterating through each digit of the encrypted message.
2. Raise each digit to the power of the number of digits in the encrypted message.
3. Sum the values of each digit raised to the power.
4. Check if the sum of the values is equal to the original input, if yes, it’s an armstrong number.
5. Add the corresponding ASCII character to the decrypted message.

NOTE: This code is not considered to be secure for encryption. This example is just provided to illustrate the idea of how the property of Armstrong number can be used in cryptography.

Super Keyword in Java
This Java Tutorial article covers one of the most important concepts in Inheritance which is Super Keyword in Java. Here, we’ll go through the uses of super keyword along with...read more
Access Modifiers in Java
Access modifiers are keywords that define the accessibility of a class and its members. Access modifiers are used in Java to control the visibility (accessibility) of classes, interfaces, variables, methods,...read more
Jump Statements in Java
In this article, we’ll cover the Jump Statements in Java, such as break, continue and return, along with examples and explanations.
Loops in Java Explained
The below article covers the iteration statements or loops in Java. It goes through the working of loops with implementation and examples.
Conditional Statements in Java
The below article goes through the Conditional Statements in Java. It covers if, if-else, nested if-else, and switch statements with examples.
Reverse a String in Java
Reversing a string is a common programming problem given while learning how to code and invoke logical thinking. However, there are more than one ways to solve this problem. The...read more
Have you ever wondered how Java performs calculations, makes decisions, or manipulates data so efficiently? This is where Java operators come into play. Operators in Java are special symbols that...read more
Understanding Variables in Java
Have you ever wondered how data is stored and manipulated in Java programs? Variables in Java are the answer, acting as containers for data values. Each variable is defined with...read more
Getting Started with Java Hello World Program
Do you know the significance of the "Hello World" program in Java? It's the first step for many into the world of programming, serving as a simple yet profound introduction...read more
Difference Between JDK, JRE, and JVM
Have you ever wondered about the backbone of Java programming? The JDK (Java Development Kit) equips developers with tools for Java application development, the JRE (Java Runtime Environment) enables the...read more
What is Serialization in Java?
Greetings, Java programmers, if you are facing a problem understanding Serialization in Java, then you have just landed in the right place. Here you will understand the core concept of...read more
Difference Between List and Set
In this article, we will briefly cover what lists and sets are in Java and Python, the difference between them, and the features of lists and sets.
Binary Search in Java
Master the fundamental concept of binary search in Java with our comprehensive article. Learn how to efficiently sort and search data, understand the logic behind it, and apply it in...read more
Factorial program in Java
This article will teach you how to find factorial using JAVA language. Factorial is calculated using recursion and loops like for and while loop.
Break and Continue in Java
In Java programming, there are two helpful tools called ‘break’ and ‘continue.’ They make managing loops easier. With ‘break,’ you can stop a loop before it finishes, based on certain...read more

## FAQs

What is an Armstrong number?

An Armstrong number is a number that is equal to the sum of the cubes of its own digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

Can you check for Armstrong number for negative or decimal numbers?

Armstrong number is only defined for positive integers, So, you can not check for negative or decimal numbers.

How to check Armstrong number for a large number?

The logic is the same as with small numbers, but you need to use a larger data type like long or BigInteger to hold the large number and result of the cubing and summing.

How to determine the length of a number in Java?

To determine the length of a number in Java, you can convert the number to a String and then use the length() method to get the number of digits. This method works for both integers and longs.

Is it necessary to check for the length of the input number?

Yes, it is necessary to check for the length of the input number, because the length of the input number is used to calculate the sum of cubes of the digits of the number.

Are there any limitations of this method?

This method has the limitation of being able to work only for positive integers as Armstrong numbers are defined for positive integers. Additionally, this method may suffer from performance issues for very large numbers, because it performs the cubing and summing operation for each digit of the number.

What is the time complexity of checking an Armstrong number?

The time complexity of checking an Armstrong number is O(k), where k is the number of digits in the number. This is because the function needs to iterate over each digit to compute the sum of the digits raised to the power of k.

Are there any limitations to the Armstrong number program in Java?

The main limitation is the range of the data type used (e.g., int or long). If the number exceeds the maximum value of the data type, it can lead to incorrect results or overflow errors. Additionally, the algorithm's efficiency decreases as the number of digits increases.

Can the Armstrong number program be optimized for performance?

While the basic algorithm is straightforward, optimizations can include memorization of the powers of digits if the function is called multiple times. For single checks, the algorithm is already quite efficient.