Identifying Armstrong Numbers in Java

06 May 2023 Balmiki Mandal 0 Core Java

Armstrong Numbers in Java

Armstrong numbers, also known as Narcissistic numbers, are numbers that are equal to the sum of their own digits raised to a power. In Java, you can use a simple algorithm to determine if a number is Armstrong or not. This blog post will explain how to do this in Java.

Algorithm for Determining Armstrong Numbers

The algorithm for determining if a number is an Armstrong number is as follows:

  1. Find the length of the number (the number of digits).
  2. Take each digit and raise it to the corresponding power.
  3. Sum the digits raised to the corresponding power.
  4. If the sum is equal to the original number, then it is an Armstrong number.

Java Code Example

Here is a simple Java code example that implements the algorithm above to check if a given number is an Armstrong number.

public class Armstrong {
    public static boolean isArmstrong(int num) 
    {
        int number = num; 
        int no_of_digits = String.valueOf(number).length(); 
        int sum = 0;
     
        while(number != 0) 
        { 
            int digit = number % 10; 
            int pow = (int) Math.pow(digit, no_of_digits); 
            sum += pow; 
            number /= 10; 
        } 
     
        // If the number and its sum of powered digits is equal,  
        // then it is an Armstrong number 
        if (sum == num) 
            return true; 
     
        return false; 
    } 
 }

Conclusion

Using the algorithm and Java code provided above you should now be able to check if a given number is an Armstrong number. This algorithm can be used as a basic introduction to algorithms in Java.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.