Examples
- Leap Year Program in Java (Check Leap Year or Not)
- Check Number is Positive or Negative in Java (4 Ways)
- Java Program to Check Character is Alphabet or Not
- Armstrong Number Program in Java (for loop, Recursion)
- Print Prime Numbers Between 1 to N in Java (1 to 100)
- Java Program for Palindrome Number (Palindrome Code)
- Sum of n Natural Numbers in Java (Programs & Explanation)
- Java Multiplication Table Program (Loops, 2D Array) 5 Ways
- Find GCD of Two Numbers in Java (HCF Program)
- GCD of Three Numbers in Java (HCF of 3 Numbers Program
- GCD of Array in Java (GCD of n Numbers Program)
- LCM of Two Numbers in Java (LCM Program and Code)
- LCM of Three Numbers in Java (Easy Programs)
- LCM of n Numbers in Java (LCM of Array of Numbers)
- How to Print A to Z in Java? 3 Ways to Print Alphabets
Armstrong Number Program in Java (for loop, Recursion)
In number theory and programming, Armstrong numbers stand as a captivating mathematical phenomenon. These numbers, also known as Narcissistic numbers or pluperfect digital invariants, possess a unique property that continues to intrigue mathematicians and programmers alike.
In this tutorial, we will learn what are Armstrong numbers in Java, know the mathematics behind them, and guide you through the process of writing a Java program to identify them.
What is Armstrong Number in Java?
An Armstrong number is a number that is equal to the sum of its own digits raised to the power of the number of digits in the number itself.
In other words, if you have an n-digit number, each digit is raised to the nth power, and the sum of these values equals the original number.
For example, let's consider the number 153:
It has three digits: 1, 5, and 3.
Each digit raised to the power of 3 (the number of digits) is calculated as follows:
1^3 = 1
5^3 = 125
3^3 = 27
The sum of these values is 1 + 125 + 27 = 153.
Use Cases of Armstrong Number Program in Java
-
Data Validation: Armstrong number programs can be used to check the integrity of data, ensuring that numbers provided by users or generated within a program meet certain criteria. If an input is expected to be an Armstrong number, the program can verify its authenticity.
-
Cryptographic Applications: In certain cryptographic algorithms, Armstrong numbers are used to enhance the security of encryption and decryption processes. Identifying these numbers can be a vital step in encryption key generation.
-
Algorithm Testing: Armstrong number programs can be utilized as test cases for algorithm validation and correctness. They provide a controlled dataset for verifying the behavior of mathematical operations and functions.
-
Educational Tools: Teaching and learning the fundamentals of programming and number theory are made more engaging with Armstrong number programs. They serve as excellent examples to illustrate concepts like loops, conditionals, and mathematical operations.
In this tutorial, let’s learn and practice the Java program for Armstrong number, using different methods, like for loop, recursion, and more.
Concepts to Learn:
Armstrong Number in Java Using for loop
Here is a Java program for armstrong number using for loop:
Code
public class ArmstrongNumberExample {
public static void main(String[] args) {
int startRange = 1;
int endRange = 1000;
System.out.println("Armstrong numbers in the range from " + startRange + " to " + endRange + ":");
for (int i = startRange; i <= endRange; i++) {
if (isArmstrongNumber(i)) {
System.out.println(i);
}
}
}
// Function to check if a number is an Armstrong number
public static boolean isArmstrongNumber(int num) {
int originalNum = num;
int numDigits = (int) Math.log10(num) + 1;
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += Math.pow(digit, numDigits);
num /= 10;
}
return sum == originalNum;
}
}
Output
Armstrong numbers in the range from 1 to 1000:
1
2
3
4
5
6
7
8
9
153
370
371
407
Explanation
-
We define a class named ArmstrongNumberExample.
-
Inside the main method, we specify the range of numbers within which we want to find Armstrong numbers. In this example, we are looking for Armstrong numbers between 1 and 1000.
-
We use a for loop in Java to iterate through the numbers in the specified range.
-
For each number, we call the isArmstrongNumber function to check if it's an Armstrong number.
-
The isArmstrongNumber function calculates whether a number is an Armstrong number or not.
-
Finally, we check if sum is equal to the originalNum to determine if it's an Armstrong number.
Program for Armstrong Number in Java Using while loop
Here's a Java program to check Armstrong number using while loop:
Code
import java.util.Scanner;
public class ArmstrongNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
int originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0) {
remainder = originalNumber % 10;
result += Math.pow(remainder, 3); // For a 3-digit Armstrong number, use Math.pow(remainder, 3)
originalNumber /= 10;
}
if (result == number) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}
}
Output
Enter a number: 243
243 is not an Armstrong number.
Explanation
-
We begin by taking input from the user, which is the number we want to check for being an Armstrong number.
-
We initialize variables originalNumber, remainder, and result. originalNumber is used to store the original input, remainder to store the remainder when dividing by 10 (i.e., individual digits), and result to accumulate the sum of digits raised to the power of 3.
-
Inside the while loop, we iterate through each digit of the originalNumber and add the cube of each digit to the result. This is done using Math.pow(remainder, 3) because Armstrong numbers of the 3-digit variety have their digits raised to the power of 3.
-
We update originalNumber by dividing it by 10, effectively removing the last digit.
-
After the loop, we compare result with the original number. If they are equal, we print that the number is an Armstrong number; otherwise, we print that it's not.
Armstrong Number Program in Java Using Recursion
Here's a Java program for Armstrong number using recursion:
Code
public class ArmstrongNumberRecursionExample {
public static void main(String[] args) {
int number = 153;
if (isArmstrongNumber(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}
// Function to check if a number is an Armstrong number using recursion
public static boolean isArmstrongNumber(int num) {
int numDigits = (int) Math.log10(num) + 1;
int sum = calculateArmstrongSum(num, numDigits);
return sum == num;
}
// Helper function to calculate the sum of digits raised to the power of numDigits using recursion
public static int calculateArmstrongSum(int num, int numDigits) {
if (num == 0) {
return 0;
}
int digit = num % 10;
return (int) Math.pow(digit, numDigits) + calculateArmstrongSum(num / 10, numDigits);
}
}
Output
153 is an Armstrong number.
Explanation
-
We define a class named ArmstrongNumberRecursionExample.
-
In the main method, we specify the number (153) that we want to check for being an Armstrong number.
-
We call the isArmstrongNumber function to check if the given number is an Armstrong number.
-
The isArmstrongNumber function checks whether a number is an Armstrong number or not.
-
The calculateArmstrongSum helper function recursively calculates the sum of digits raised to the power of numDigits.
-
Depending on whether the number is found to be an Armstrong number or not, we print an appropriate message to the console.
Armstrong Number Program in Java Without Loops and Recursion
This program checks whether a given number is an Armstrong number using mathematical formulas without recursion or loops, making it an efficient way to determine Armstrong numbers.
Code
import java.util.Scanner;
public class ArmstrongNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}
static boolean isArmstrong(int num) {
int original = num;
int numberOfDigits = (int) Math.log10(num) + 1;
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += Math.pow(digit, numberOfDigits);
num /= 10;
}
return sum == original;
}
}
Output
Enter a number: 242
242 is not an Armstrong number
Explanation
-
Like in the previous methods, we begin by taking input from the user, which is the number we want to check for being an Armstrong number.
-
We then call the isArmstrong method and pass the number as an argument.
-
In the isArmstrong method, we first store the original value of num because we will be modifying it.
-
We calculate the number of digits in num using (int) Math.log10(num) + 1. This gives us the count of digits, which is used in the Armstrong number calculation.
-
We initialize a variable sum to accumulate the sum of powered digits.
-
Inside the while loop, we iterate through each digit of num using the modulo operator and raise each digit to the power of numberOfDigits, adding it to sum.
-
We then divide num by 10 to move to the next digit.
-
After the loop, we check if sum is equal to the original num. If they are equal, we return true, indicating that the number is an Armstrong number; otherwise, we return false.
-
Finally, in the main method, we print the result based on whether isArmstrong returns true or false.
Learn Next: