Armstrong Number in Java – A Complete Guide with Examples

Updated on September 24, 2024

Article Outline

If we were to discuss appealing numbers in mathematics, Armstrong numbers would be one of the options that often appear. Ever wondered what an Armstrong number is? Perhaps you came across this in a coding interview or when working on assignments in your studies. But what actually makes a number an Armstrong number, and to what extent is it significant to us?

 

Armstrong’s number is also called a Narcissistic number. It is a really interesting idea that connects mathematics and programming in a rather unconventional manner. Armstrong numbers are specifically self-referential, and thus, both mathematicians and coders can find this property very engaging. In this article, we’ll talk about Armstrong Number in Java.

Detailed Explanation and Importance of Armstrong Numbers with Unique Examples

Armstrong numbers are great for understanding how mathematical concepts apply to programming. The great thing about these problems is that they are very useful when exercising our logical thinking and coding abilities.

 

For a number to be an Armstrong number:

 

  1. Determine the number of digits (n).
  2. Raise each digit to the power of n.
  3. Sum these values.
  4. If the sum equals the original number, it’s an Armstrong number.

 

Let’s look at a few examples to clarify this concept:

 

Example 1: 9474

  • Number of digits: 4
  • Calculation: 9^4 + 4^4 + 7^4 + 4^4 = 6561 + 256 + 2401 + 256 = 9474
  • Result: 9474 is an Armstrong number.

 

Example 2: 1634

  • Number of digits: 4
  • Calculation: 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634
  • Result: 1634 is an Armstrong number.

 

Example 3: 8208

  • Number of digits: 4
  • Calculation: 8^4 + 2^4 + 0^4 + 8^4 = 4096 + 16 + 0 + 4096 = 8208
  • Result: 8208 is an Armstrong number.

 

These examples highlight the unique self-referential property of Armstrong numbers. Their applications extend beyond mathematics; they are often used in computer science to teach concepts like loops, conditionals, and functions.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Naive Approach and Time & Space Complexity Analysis

Let’s talk about the naive approach to finding Armstrong number in Java. This approach is relatively easy but not the most effective. Nonetheless, it provides a solid foundation for comprehending the idea.

Steps Involved in the Naive Approach:

1. Count Digits:

 

  • We iterate through the number to count the digits.
  • This can be done by repeatedly dividing the number by 10 until it becomes 0.

 

2. Sum of Powers:

 

  • For each digit, calculate the power (number of digits).
  • Sum these powered values.

 

3. Compare:

 

  • Check if the sum equals the original number.

 

Here’s a Java code snippet using the naive approach:

public class Armstrong { public static void main(String[] args) { java.util.Scanner scanner = new java.util.Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); if (isArmstrong(number)) { System.out.println(number + " is an Armstrong number."); } else { System.out.println(number + " is not an Armstrong number."); } } public static boolean isArmstrong(int num) { int original = num; int sum = 0; int n = String.valueOf(num).length(); while (num > 0) { int digit = num % 10; sum += Math.pow(digit, n); num /= 10; } return sum == original; } }

Output:

output

 

ouput

Time & Space Complexity

Time Complexity:

 

O(d), where d is the number of digits of the number.

 

Reason: We have to go through each digit to determine the sum of its power.

 

Space Complexity:

 

O(1), for the most part

 

Reason: We only have a few extra variables we need to store and arithmetically manipulate.

Implementing Armstrong Number in Java Using Basic Operations

Did you ever attempt to write a Java program to determine if a given number can be called an Armstrong number? Here’s how we can do it with the use of simple mathematical operations and loops:

 

Step-by-Step Implementation

 

1. Read the Input:

 

  • We need to take a number as input from the user.

 

2. Initialise Variables:

 

  • Set up variables to store the sum and the original number.

 

3. Count the Digits:

 

  • Calculate the number of digits in the input number.

 

4. Calculate the Sum of Powers:

 

  • For each digit, raise it to the power of the total number of digits and add the result to the sum.

 

5. Compare and Output:

 

  • Check if the sum equals the original number.
  • If they match, it’s an Armstrong number.

 

Java Code Example

import java.util.Scanner; public class Armstrong { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); if (isArmstrong(number)) { System.out.println(number + " is an Armstrong number."); } else { System.out.println(number + " is not an Armstrong number."); } } public static boolean isArmstrong(int num) { int original = num; int sum = 0; int n = String.valueOf(num).length(); while (num > 0) { int digit = num % 10; sum += Math.pow(digit, n); num /= 10; } return sum == original; } }

Output:

output

 

ouput

Using Recursion to Check for Armstrong Number in Java

Ever wondered if we could use recursion to check for an Armstrong number in Java? Yes, we can. Recursion simplifies our code and makes it elegant.

 

Why Use Recursion?

 

Recursion breaks the problem into smaller, more manageable parts. Instead of using loops, we call the function within itself. It’s like solving a puzzle piece by piece.

 

Java Code Example with Recursion

import java.util.Scanner; public class Armstrong { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); if (isArmstrong(number)) { System.out.println(number + " is an Armstrong number."); } else { System.out.println(number + " is not an Armstrong number."); } } public static boolean isArmstrong(int num) { int n = order(num); return num == calculateSum(num, n); } public static int calculateSum(int num, int n) { if (num == 0) return 0; int digit = num % 10; return (int) Math.pow(digit, n) + calculateSum(num / 10, n); } public static int order(int num) { return String.valueOf(num).length(); } }

Output:

output

 

output

Efficient Java Programs for Finding Armstrong Numbers in a Range

Checking a single number is great, but what if we need to find all Armstrong numbers in a range? Let’s explore how we can efficiently do this in Java.

 

Steps to Find Armstrong Numbers in a Range

 

1. Define the Range:

 

  • Set the start and end values of the range.

 

2. Iterate Through the Range:

 

  • Use a loop to check each number in the range.

 

3. Check Each Number:

 

  • For each number, check if it is an Armstrong number using our previous methods.

 

Java Code Example for a Range

 

Here’s a Java program to find Armstrong numbers between 1 and 999:

public class ArmstrongRange { public static void main(String[] args) { int start = 1; int end = 999; System.out.println("Armstrong numbers between " + start + " and " + end + ":"); for (int i = start; i <= end; i++) { if (isArmstrong(i)) { System.out.println(i); } } } public static boolean isArmstrong(int num) { int original = num; int sum = 0; int n = String.valueOf(num).length(); while (num > 0) { int digit = num % 10; sum += Math.pow(digit, n); num /= 10; } return sum == original; } }

Output:

output

Exploring Armstrong Number in Java of Different Orders

Have you ever wondered if Armstrong numbers exist beyond the common examples like 153 or 370? They do. Armstrong numbers can exist in various orders, not just three digits.

Understanding Different Orders

An Armstrong number can be any positive integer. The important thing to remember is that the number must equal the sum of its digits, each raised to the power of the total number of digits.

 

Example of Different Orders

 

Order 4: 1634

Calculation: 1^4 + 6^4 + 3^4 + 4^4 = 1634

 

Order 5: 54748

Calculation: 5^5 + 4^5 + 7^5 + 4^5 + 8^5 = 54748

 

Java Program for Different Orders

 

Here’s a Java program to check Armstrong numbers of any order:

import java.util.Scanner; public class Armstrong { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); if (isArmstrong(number)) { System.out.println(number + " is an Armstrong number."); } else { System.out.println(number + " is not an Armstrong number."); } } public static boolean isArmstrong(int num) { int original = num; int sum = 0; int n = String.valueOf(num).length(); while (num > 0) { int digit = num % 10; sum += Math.pow(digit, n); num /= 10; } return sum == original; } }

Output:

output

 

Understanding Armstrong’s numbers of different orders helps us appreciate the variety and complexity of these numbers. It also enhances our coding and problem-solving skills.

Finding the Nth Armstrong Number in Java

Curious about finding the nth Armstrong number in Java? It’s a bit more challenging but definitely doable.

 

Steps to Find the nth Armstrong Number in Java

 

1. Initialise:

 

  • Set up a counter to keep track of how many Armstrong numbers we’ve found.

 

2. Loop Through Numbers:

 

  • Start with 1 and check each number until we find the nth Armstrong number.

 

3. Check Each Number:

 

  • Use our Armstrong number-checking function.

 

Java Code Example

import java.util.Scanner; public class NthArmstrong { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the value of n: "); int n = scanner.nextInt(); int count = 0; int number = 1; while (count < n) { if (isArmstrong(number)) { count++; } number++; } System.out.println("The " + n + "th Armstrong number is: " + (number - 1)); } public static boolean isArmstrong(int num) { int original = num; int sum = 0; int n = String.valueOf(num).length(); while (num > 0) { int digit = num % 10; sum += Math.pow(digit, n); num /= 10; } return sum == original; } }

Output

output

Conclusion

In this blog, we explored how to implement an Armstrong number in Java. We learned how to use step-by-step algorithms, basic operations, and recursion in checking, as well as how to determine Armstrong numbers from a given range.

 

Furthermore, we looked into distinct orders of Armstrong numbers and the method for determining the Nth Armstrong number. Armstrong numbers are more than just a mathematical identity. They are an excellent opportunity to sharpen your programming and problem-solving abilities.

FAQs
An Armstrong number is equal to the sum of its own digits, raised to the power of the number of digits.
No, Armstrong numbers are defined only for positive integers.
Armstrong numbers are mainly used for educational purposes, such as teaching algorithms and improving logical thinking.
The order of a number is determined by the number of digits. For example, 153 has an order of 3.

Updated on September 24, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved