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());
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!