Find Armstrong Numbers in a Given Range in java

               Armstrong Number is a number which has a unique feature in it. When you take cube of each digit and sum it, it gives the same number.

Eg:

153 = 13 +53 +33 = 1+125+27 = 153.

Java implementation of finding Armstrong Number in the given range:

  • It starts with including the built-in header file.
  • Create a class with two functions  itArmstrong() and findArmstrongNos().
  • itArmstrong() – it splits each digit separately and raise the power to 3 .
  • ‘findArmstrongNos()’ – it finds the Armstrong number in the given range.
  • ‘main()’ – reads the input from the user to starting and ending of the range.
  • It calls the ‘findArmstrongNos()’ function.

Program:

import java.util.Scanner;

public class ArmstrongNoInRangeEg {

       public static boolean itArmstrong(int n) {

        int originalNo = n, sum = 0, digit = 0;

        // Code to count the number of digits

        int temp = n;

        while (temp > 0) {

            digit++;

            temp /= 10;

        }

        // To find the sum of digits raised to the power of digits

        temp = originalNo;

        while (temp > 0) {

            int digi = temp % 10;

            sum += Math.pow(digi, digit);

            temp /= 10;

        }

        return sum == originalNo;

    }

     // Let us find Armstrong numbers in a given range

    public static void findArmstrongNos(int s, int e) {

        System.out.println("Armstrong Numbers between " + s + " and " + e + ":");

        for (int no = s; no <= e; no++) {

            if (itArmstrong(no)) {

                System.out.print(no + " ");

            }

        }

        System.out.println();

    }

    public static void main(String[] args) {

        Scanner s1 = new Scanner(System.in);

        // Input statements

        System.out.print("Enter the start of range: ");

        int st = s1.nextInt();

        System.out.print("Enter the end of range: ");

        int en = s1.nextInt();

        findArmstrongNos(st, en);

        s1.close();

    }

}

Output:

C:\raji\blog>javac ArmstrongNoInRangeEg.java

C:\raji\blog>java ArmstrongNoInRangeEg

Enter the start of range: 123

Enter the end of range: 1045

Armstrong Numbers between 123 and 1045:

153 370 371 407

That’s it. The java program to find Armstrong number in the given range is done. Hope, this code is easily understandable to you. Keep Coding!!!

No comments:

Post a Comment