user56690 user56690 - 5 months ago 28
Java Question

java any digit armstrong number

i have written the below code for getting a three digit armstrong number.

public class test {
public static void main(String args[]){

for (int i = 100; i <= 999; i++){
int firstDigit = (i / 100);
int secondDigit = (i % 100) / 10;
int thirdDigit = (i % 10);
if ((firstDigit * firstDigit * firstDigit) +
(secondDigit * secondDigit * secondDigit) +
(thirdDigit * thirdDigit * thirdDigit) == i) {

System.out.println("this is a armstriong number - "+i);
}
} } }


I am trying to get a ANY digit armstrong based on users input, but i am ending up writing too much loops and code.

Please help.
Thanks in advance.

Answer

The following code check if the scanned number (on console) is a Armstrong number. I've tested it, it works fine.

TEST IN CONSOLE

import java.util.Scanner;

class ArmstrongNumber
{
   public static void main(String args[])
   {
      int n, sum = 0, temp, remainder, digits = 0;

      Scanner in = new Scanner(System.in);
      System.out.println("Input a number to check if it is an Armstrong number");      
      n = in.nextInt();

      temp = n;

      // Count number of digits

      while (temp != 0) {
         digits++;
         temp = temp/10;
      }

      temp = n;

      while (temp != 0) {
         remainder = temp%10;
         sum = sum + power(remainder, digits);
         temp = temp/10;
      }

      if (n == sum)
         System.out.println(n + " is an Armstrong number.");
      else
         System.out.println(n + " is not an Armstrong number.");         
   }

   static int power(int n, int r) {
      int c, p = 1;

      for (c = 1; c <= r; c++) 
         p = p*n;

      return p;   
   }
}

Source here.


WITH A FUNCTION

If you need to use it as a function, please try this. The n param is the number you want to check. My function return true if it is an Armstrong number, else it returns false.

public boolean isArmstrongNumber(int n) {
    int sum = 0, temp = n, remainder, digits = 0;
    while (temp != 0) {
         digits++;
         temp = temp/10;
      }

      temp = n;

      while (temp != 0) {
         remainder = temp%10;
         sum = sum + power(remainder, digits);
         temp = temp/10;
      }
      if (n == sum) //Armstrong number
          return true;
       else //Not Armstrong number
          return false;
}