Armstrong numbers are a popular programming concept often used in Java exercises to teach logic and number manipulation. They are frequently asked in coding interviews and college lab exams to assess your understanding of loops, conditionals, and digit operations. If you are a B.Tech student just starting out, chances are you’ve come across this problem in class or in practice sets. This article will walk you through everything about Armstrong numbers from the basic definition and logic to implementations using loops, recursion, and Java 8 Streams.
Table of Contents:
What is an Armstrong Number?
When each digit of a number, raised to the power of the total number of digits, contributes to a sum that perfectly reconstructs the original number, then the number is called an Armstrong Number. Armstrong number problems help to strengthen the understanding of loops, conditionals, and number manipulation, and are commonly used in coding interviews to break down a problem, handle digits, and write clean logic without using built-in shortcuts. The logic behind the Armstrong number is the digit extraction and number-based validation, which is useful in various use cases like:
- Checksums and validation algorithms where digit-level computation is key.
- Cryptography for designing numeric puzzles or obfuscation techniques.
For an n-digit number:
Armstrong number: abcd = an+ bn+ cn+ dn
Where:
- a, b, c, and d are the digits of the number.
- n is the total number of digits.
Now, let us break down the above formulae.
Example 1: 153
- Number of digits = 3
- Digits: 1, 5, 3
13+53+33 = 1+125+27 = 153
Since the sum equals the original number, 153 is an Armstrong number.
Example 2: 370
- Number of digits = 3
- Digits: 3, 7, 0
33+73+03 = 27+343+0 = 370
Since the sum equals the original number, 370 is an Armstrong number.
Example 3: 123
- Number of digits = 3
- Digits: 1, 2, 3
13+23+33 = 1+8+27 = 36
Since the sum is not equal to the original number, 123 is an Armstrong number.
How to Check Armstrong Number in Java?
We can check if the number is an Armstrong number or not by the following flowchart.
Step-by-Step Explanation of the Armstrong Number Flowchart
Now, let us explain the working of the above flowchart in detail.
- Start: The program begins execution.
- Read Input Number n: Accept a number from the user to check if it’s an Armstrong number.
- Set original = n: Store the original value of the input number because n will be modified later in the loop. This helps in comparing at the end.
- Count Number of Digits, d: Count how many digits are in the input number. This digit count (d) is used as the exponent (power) while computing the Armstrong condition.
- Initialize result = 0: A variable result is initialized to accumulate the sum of powered digits.
- While n ≠ 0 (Loop through digits): This loop processes each digit of the number:
- digit = n % 10, extract the last digit of the number using the modulus operator.
- result += digit^d, raise the digit to the power of d (number of digits) and add it to result.
- n = n / 10, remove the last digit from n (integer division), which moves to the next digit.
- Compare result == original?: After the loop, check if the sum (result) is equal to the original number.
- If Equal: Print: “It is Armstrong”, if the number satisfies the Armstrong condition.
- If Not Equal: Print: “Not an Armstrong number”, if the number does not meet the criteria.
- End: Program ends.
Java Programs to Check Armstrong Numbers
Below are some Java programs to check Armstrong Numbers.
Example 1: Check Armstrong Number in Java for a 3-digit number
This program checks for Armstrong numbers in Java for 3-digit numbers. The sum of the cubes of each digit should be equal to the number itself; then only can we say it is an Armstrong number.
Output:
This Java program checks if a 3-digit number is an Armstrong number by summing the cubes of its digits and comparing the result to the original number. If they match, it prints that the number is an Armstrong number.
Example 2: Check Armstrong Number in Java for n digits
This program checks for Armstrong numbers in Java for n-digit numbers. As mentioned above, to check whether a number is Armstrong or not, the sum of the digits to the power of the total number of digits is equal to the number itself.
Output:
This Java program checks whether any n-digit number is an Armstrong number by calculating the number of digits and summing each digit raised to that power. If the sum equals the original number, it’s an Armstrong number.
Example 3: Armstrong Number in Java using Loops
This program checks for an Armstrong Number in Java using loops. Here in this code, we are using a for loop. A for loop is a structure that repeats a block of code a fixed number of times.
Output:
This program checks if a number is an Armstrong number by manually calculating powers using a loop instead of Math.pow(). It counts the digits, computes each digit raised to that count using a for loop, sums them, and compares with the original number.
Example 4: Armstrong Number in Java Using Recursion
This program checks for an Armstrong Number in Java using recursion. Recursion is a programming technique where a function calls itself to solve a specific part of the program.
Output:
This program uses recursion to check if a number is an Armstrong number by recursively counting its digits, calculating powers, and summing the powered digits. It then compares the result with the original number to determine the outcome.
Example 5: Armstrong Number in Java Using Java 8 Streams
This program checks for Armstrong numbers in Java using Java 8 streams. Java 8 introduced streams to process collections like arrays or lists in a readable, declarative, and efficient way.
Output:
This program uses Java 8+ Streams to check for an Armstrong number by converting the number to a stream of digits, raising each to the power of the total digits, summing them, and comparing the sum with the original number.
Get 100% Hike!
Master Most in Demand Skills Now!
Time and Space Complexity analysis
Now, let us consider the time and space complexity of calculating an Armstrong number.
Time Complexity
Let d be the number of digits in the number. Then,
1. Best Case (O(1)): When the number is a single-digit number, then
- Number of digits d = 1,
- Counting the digits is O(1)
- Calculating the power of each digit is O(1).
Since everything happens in constant time, total time complexity is O(1).
2. Average Case (O(log n)): For a random n-digit number,
- Number of digits d is log₁₀(n)
- Counting digits is O(log n)
- Calculating the power of each digit is O(d) = O(log n)
Each digit is processed once, and powering a small digit (0–9) takes constant time. So, total time complexity is O(log n).
3. Worst Case (O(log n)): For a very large number (e.g., with 10+ digits),
- d = log₁₀(n) is large
- Counting digits is O(log n)
- Calculating the power of each digit is O(d) = O(log n).
Still, we process each digit only once with constant-time operations. So, total time complexity: O(log n)
Space Complexity
Only a constant number of variables are used (e.g., for storing digit, result, and power), and no extra data structures like arrays, strings, or lists are required. So, total space complexity is O(1) due to constant space used.
Case |
Time Complexity |
Space Complexity |
Best |
O(1) |
O(1) |
Average |
O(log n) |
O(1) |
Worst |
O(log n) |
O(1) |
Difference between Armstrong Number and Narcissistic Number
The difference between an Armstrong number and a Narcissistic Number:
Features |
Armstrong Number |
Narcissistic Number |
Definition |
An Armstrong number is the one that equals the sum of its own digits, each raised to the power of the total number of digits. |
It is the same as the Armstrong number -the sum of the digits raised to the power of the number of digits. |
Used In |
Used in computer science, programming, and Java tutorials. |
Used in Mathematics and Number Theory |
Common In |
It is common in coding interviews and competitive programming. |
It is common in math problems and theoretical discussions. |
Name Origin |
It is named after Michael F. Armstrong. |
It refers to the self-referential nature of the number. |
Real World Cases
The Armstrong numbers in Java are useful in various scenarios, like in education or computation. Some of the real-world cases, along with their descriptions, are given below:
Use Cases |
Description |
Computer Science Education |
The basic programming concepts, such as loop, recursion, digit extraction, and conditionals, are taught using Armstrong numbers. |
Coding Interviews |
To test the understanding of number manipulation and logic building in coding in the beginner level. |
Math Puzzles and Games |
Due to its unique properties, it is featured in number puzzles, math-based games, and competitive programming problems. |
Algorithm Design Practice |
It is used for practicing algorithms involving digit processing, such as checking for palindromes or reversing numbers. |
Test Cases in Software QA |
To validate numeric processing functions and for creating non-linear logic test cases, Armstrong number checks are used as dummy validation rules. |
Handling Edge Cases in Armstrong Programs
To make our logic robust and bug-free, it is very important to account for edge cases while writing an Armstrong number program. Some key cases are listed below:
- Negative Numbers: Armstrong numbers can only be used to check positive integers, but to fix this problem, we can add a check to reject negative input. The negative numbers are rejected early with the statement “if (n < 0)” in the code.
- Single-Digit Numbers: Every single-digit number, 0-9, is an Armstrong number, as n^1 = n.
- Zero (0): Zero is an Armstrong number. We have to ensure that the code does not skip or mishandle it.
- Very Large Numbers: If not handled properly, large inputs can cause overflow in int and even precision loss in Math.pow() due to floating-point arithmetic; to fix this problem, use long or BigInteger.
- Non-Numeric Input: If we enter non-numeric input, like abc, instead of a number, then the “Scanner.nextInt()” will throw InputMismatchException. To fix this problem, use a try-catch block for safer input handling.
- Floating Point Numbers: Armstrong logic is applicable only to integers; to avoid this problem, reject decimal input if it is not an integer.
Common Errors and Best Practices in Armstrong Number Programs
Below are some common errors and best practices one should follow while dealing with Armstrong numbers in Java.
Common Errors in Armstrong Number Programs:
Common errors occurring in Armstrong number programs are as follows:
- Math.pow() generates a double. If you do a comparison with the generated double, and the number is an int, there can be precision issues that can mess things up. To prevent this, don’t forget to cast your return to int.
- The error can arise from assuming a fixed digit count.
- Programs often don’t filter out the negatives, and the error occurs for the reason that Armstrong’s logic does not apply to negatives.
- When the users enter non-numeric characters, the “Scanner.nextInt()” throws InputMismatchException, due to which the program crashes.
- If we fail to close the Scanner object, then it can cause resource/memory leaks or warnings in IDEs.
- We should use proper variable names to make the code understandable and easily maintainable.
Best Practices for Armstrong Number Programs:
Best practices one should follow while using armsrong number are as follows:
- To print int, always cast Math.pow() like
result += (int) Math.pow(digit, digitCount);
This gives the output as an integer without any unexpected behavior due to floating-point precision.
- We should count the digits for any size number by using a loop or String.valueOf(n).length().
- To safely handle invalid input, we should use try-catch blocks or Scanner.nextInt().
- We should add conditional checks to allow only non-negative integers, as Armstrong applies only to positive integers.
- To clean functions, we should separate digit counting, power summation, and validation to modularize logic into reusable methods.
- To prevent potential memory and resource leaks, we should close the scanner object after use.
Free Java Course for Beginners
Jump in, have fun learning and become job-ready
Conclusion
From the above article, we have learned that Armstrong number programs in Java are an excellent way to practice core programming concepts such as loops, conditional statements, recursion, digit extraction, and number reversal. These exercises help strengthen your foundation in Java and improve your ability to break down and solve algorithmic problems efficiently. By mastering the logic behind Armstrong numbers, developers can build habits of clean, precise coding, effective input validation, and strong algorithmic thinking skills that are highly valuable in coding interviews, competitive programming, and real-world software development.
Useful Resources:
Armstrong Numbers in Java – FAQs
Q1. Why is 153 an Armstrong number?
Because the sum of its digits each raised to the power of three equals the number itself.
Q2. Are all 1-digit numbers Armstrong numbers?
Yes, because each digit to the power of 1 is the number itself.
Q3. Can a negative number be Armstrong?
No, Armstrong numbers are only defined for non-negative integers.
Q4. What is the largest known Armstrong number?
The largest known is a 39-digit number: 115132219018763992565095597973971522401.
Q5. What are 2-digit Armstrong numbers?
None, because no 2-digit number equals the sum of its digits each raised to the power of 2.