# Armstrong Number in Java using Different Methods

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 1^{3} + 5^{3} + 3^{3} =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; }}

**Armstrong Number in JAVA** **Using 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

- Obtains the last digit of the number by taking the remainder of
- 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;}

**Armstrong Number in JAVA** **Using 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); }}

**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:**

- Take a plaintext message as input from the user.
- 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.
- Concatenate the resulting values to form the encrypted message.
- Output the encrypted message to the user.

**Decryption:**

- Take an encrypted message as input from the user.
- Iterate through each digit of the encrypted message.
- Raise each digit to the power of the number of digits in the encrypted message.
- Sum the values of each digit raised to the power.
- Check if the sum of the values is equal to the original input, if yes, it’s an armstrong number.
- Add the corresponding ASCII character to the decrypted message.
- 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; }}

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

- Converting each character in the plaintext message to its corresponding ASCII value.
- Raising each ASCII value to the power of the number of characters in the message.
- 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:

- Iterating through each digit of the encrypted message.
- Raise each digit to the power of the number of digits in the encrypted message.
- Sum the values of each digit raised to the power.
- Check if the sum of the values is equal to the original input, if yes, it’s an armstrong number.
- 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.

## 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.

**About the Author**

Experienced AI and Machine Learning content creator with a passion for using data to solve real-world challenges. I specialize in Python, SQL, NLP, and Data Visualization. My goal is to make data science engaging an... Read Full Bio

## Comments

(1)

S

2 weeks ago

Report Abuse

Reply to Satya Bhardwaj