简体   繁体   中英

Java any digit Armstrong number

Following is my 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 any digit Armstrong based on users input, but I am ending up writing too many loops and excess code.

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;
}

just change max value of arm_num you will get Armstrong number between 0 to arm_num

for(int arm_num = 0 ; arm_num < 100000 ; arm_num++)
        {
            String[] data = String.valueOf(arm_num).split("(?<=.)");
            int lngth = String.valueOf(arm_num).length();

            int arm_t_num = 0;

            int ary[] = new int[lngth];

            for(int i = 0 ; i < lngth ; i++)
            {
                ary[i] = Integer.parseInt(data[i]);

                for(int x = 0 ; x < lngth-1 ; x++)
                {
                    ary[i] = ary[i] * Integer.parseInt(data[i]);
                }

                arm_t_num+=ary[i];
            }

            if(arm_num == arm_t_num)
            {
                System.out.println("Number is ArmStrong : "+arm_num);
            }
        }

Please try using below method

public static Boolean isArmstrongNumber(int number) {
    int n = number;
    List<Integer> lst = new ArrayList<Integer>();

    // to find digit and putting in list
    while (number > 0) {
        lst.add(number % 10);
        number = number / 10;
    }

    Long sum = 0L;
    for (Integer integer : lst)
        sum += (Long) Math.round(Math.pow(integer, lst.size()));
    return sum.intValue() == n ? true : false;
}

Using Java8, you could create a IntStream to generate the Armstrong Numbers.

The first step could be to create a function to validate if a number is a Armstrong number:

public class ArmstrongNumbersGenerator {    

    // Get the next n armstrong numbers starting at a given number         
    public static int[] get(int start, int count) {         
        return IntStream.iterate(start, i -> i + 1)
            .filter(ArmstrongNumbersGenerator::isArmstrongNumber)
            .limit(count)
            .toArray();
    }

    // Get all the armstrong numbers in a given range
    public static int[] inRange(int start, int end) {
        return IntStream.range(start, end)
                .filter(ArmstrongNumbersGenerator::isArmstrongNumber)
                .toArray();
    }

    // Validate if a number is a armstrong number
    public static boolean isArmstrongNumber(int number) {
        int remainingDigits = number;
        int cubesTotal = 0;
        while(remainingDigits > 0) {
            int currentDigit = remainingDigits % 10;
            remainingDigits = remainingDigits / 10;
            cubesTotal += currentDigit * currentDigit * currentDigit;
        }
        return cubesTotal == number;
    }
}

Example usage:

System.out.println(Arrays.toString(ArmstrongNumbersGenerator.inRange(0, 10_000)));
Output: [0, 1, 153, 370, 371, 407]

System.out.println(Arrays.toString(ArmstrongNumbersGenerator.get(200, 2)));
Output: [370, 371] 

I had written a program for getting all Armstrong Numbers between 1 and 10_000_000 which I had gotten reviewed on Code Review. Following is a minimalist implementation for finding the Armstrong Number using based on the suggestions I received there:

IntStream.range(1, 10_000_000)
            .filter((n) -> {
                final String number = Integer.toString(n);
                return number.chars()
                    .mapToDouble(v -> Math.pow(v - '0', number.length()))
                    .sum() == n;
            }).forEach(System.out::println);

Output:

1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
54748
92727
93084
548834
1741725
4210818
9800817
9926315

Links to the review questions:


This is not a fast solution to the problem. You could use parallel for reducing the execution time. The only drawback being that the final output won't be in order.

IntStream.range(1, 10_000_000)
            .parallel()    // For reducing execution time.
            .filter((n) -> {
                final String number = Integer.toString(n);
                return number.chars()
                        .mapToDouble(v -> Math.pow(v - '0', number.length()))
                        .sum() == n;
            }).forEach(System.out::println);

Output:

1741725
9800817
9926315
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
54748
92727
93084
4210818
548834

Following is a Caliper Test report for the given range of 1 to 10_000 :

 0% Scenario{vm=java, trial=0, benchmark=Parallel} 1933923.45 ns; ?=119465.91 ns @ 10 trials
50% Scenario{vm=java, trial=0, benchmark=Normal} 6161598.59 ns; ?=29084.33 ns @ 3 trials

benchmark   ms linear runtime
 Parallel 1.93 =========
   Normal 6.16 ==============================

Try This code, U can even ask user to input the number to test for Armstrong.

class Test{  
  public static void main(String[] args)  {  
    int c=0,a,temp;  
    Scanner scn = new Scanner(System.in);
  //It is the number to check armstrong
    System.out.println("Enter the number to check");
    int n=scn.nextInt();  

    temp=n;  
    while(n>0)  
    {  
    a=n%10;  
    n=n/10;  
    c=c+(a*a*a);  
    }  
    if(temp==c)  
    System.out.println("armstrong number");   
    else  
        System.out.println("Not armstrong number");   
   }  
}  

I think my solution is easier...

int n = in.nextInt();
for(int i = 10; i<=n; i++){
    int x=i; sum = 0;
    while(x>0){
      sum+ = (x%10)(x%10)(x%10);
      x/=10;
}
if(sum==i)
System.out.println(i+" ");
}

You just need to provide a limit value, so the following program will search all the Armstrong Numbers from 1 to Limit

    int sum =0, tenspower =1;
    Int limit =1000000001;

    int arr[] = new int[10];


    for (int i=1;i<limit;i++){
        String[] str = String.valueOf(i).split("");


        for(int k=0; k< str.length; k++ ){

            sum = (int) (sum + Math.pow(Integer.parseInt(str[k]), str.length))   ;

                }


        if(sum==i){
            System.out.println(sum);

        }

        sum =0 ;
        str =null;

    }
/* 
 * To Find The Given Number is Armstrong Or Not.
 */
package Test_2_Feb;

import java.util.Scanner;
public class ArmStrongNo {


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int count =0,rem,Sum =0,pow;
        System.out.println("\t\tWelcome To the Program To Find Armstrong Number");
        System.out.println("\t\t------- -- --- ------- -- ---- --------- ------");
        System.out.println("Enter The Number ");
        int no = sc.nextInt();
        int temp = no;
        pow = no;
        while(no>0)
        {
            rem = no%10;

            while(pow>0)
            {
                pow = pow/10;
                count++;
                }

            no = no/10;

            if(count!=0)
            {
                Sum = (int) (Sum+Math.pow(rem, count));
            }

        }
        if(temp==Sum)
        {
            System.out.println("\tGiven Number : " +temp + "\n\tSum Of Number : " + Sum + "\n\tSo, The Given Number (" + temp + ") is An armstrong Number");
        }
        else
        {
            System.out.println("\tGiven Number : " +temp + "\n\tSum Of Number : " + Sum + "\n\tSo, The Given Number (" + temp + ") is Not an armstrong Number");

        }

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM