LearnFrenzy
Sign in Take a free test

Control Flow Statements · Control Flow Programs · Question 3

Find Armstrong numbers in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Print all Armstrong (narcissistic) numbers below 100,000: numbers equal to the sum of their digits each raised to the number of digits.

Solution
Main.java
public class Main {
    static boolean isArmstrong(int n) {
        int digits = String.valueOf(n).length();
        int sum = 0, x = n;
        while (x > 0) {
            int d = x % 10;
            int p = 1;
            for (int k = 0; k < digits; k++) p *= d;     // d^digits without Math.pow rounding
            sum += p;
            x /= 10;
        }
        return sum == n;
    }

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (int n = 1; n < 100_000; n++) if (isArmstrong(n)) sb.append(n).append(' ');
        System.out.println(sb.toString().trim());
    }
}

Output Verified by compiling and running

1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084

153 = 1³ + 5³ + 3³. An integer power loop avoids floating-point rounding from Math.pow.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links