Home > Back-end >  Java code finds Armstrong number upto 3 digit numbers but fails on 4 digit onwards
Java code finds Armstrong number upto 3 digit numbers but fails on 4 digit onwards

Time:08-03

I just started learning java 2 days ago and tried doing an assignment to find if the three digit number was an Armstrong number or not. This code works upto 3 digit numbers and after that it fails to work on 4 digit Armstrong numbers like 1634, 8208 etc..

public class project1 {

public static void main(String[] args) {

    int number = 9474, originalNumber, remainder, result = 0;

    originalNumber = number;

    while (originalNumber != 0)
    {
        remainder = originalNumber % 10;
        result  = 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.");
}
}

CodePudding user response:

Your solution just support 3 digit numbers. If you want to change it for numbers with any digits should first count number of digits:

int numberOfDigits = 0;
while (originalNumber != 0) {
     numberOfDigits  ;
     originalNumber /= 10;
}

And then just a minor changes in your code for power of Math.pow method as:

result  = Math.pow(remainder, numberOfDigits);

The complete solution is:

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

        int number = 9474, originalNumber, remainder, result = 0;

        originalNumber = number;

        int numberOfDigits = 0;
        while (originalNumber != 0) {
            numberOfDigits  ;
            originalNumber /= 10;
        }

        originalNumber = number;

        while (originalNumber != 0) {
            remainder = originalNumber % 10;
            result  = Math.pow(remainder, numberOfDigits);
            originalNumber /= 10;
        }

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

CodePudding user response:

public class ArmstrongNumberDemo
{
 public static void main(String[] args) {
  int num = 9474, realNumber, remainder, output = 0, a = 0;
  realNumber = num;
  for(;realNumber != 0; realNumber /= 10,   a);
  realNumber = num;
  for(;realNumber != 0; realNumber /= 10){
     remainder = realNumber % 10;
     output  = Math.pow(remainder, a);
  }
  if(output == num){
     System.out.println(num   " is an Armstrong number.");
  }
  else{
     System.out.println(num   " is not an Armstrong number.");
  }
  }
 }
  • Related