4
\$\begingroup\$

Was fiddling with ; trying to write a program for getting all Armstrong Numbers between 1 and 10_000_000.

Following is my working solution:

public class ArmstrongNumbers {
 public static void main(String[] args) {
 IntStream.range(1, 10_000_000)
 .filter((n) -> {
 int c = 0, temp = n;
 while (temp > 0) {
 c += Math.pow(temp % 10, Integer.toString(n).length());
 temp /= 10;
 }
 return c == 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

Why I'm here:

  • Can this be made shorter?
  • Can any other Java 8 concept be used here?
  • Can the use of the while loop be avoided and a stream be used somehow (given that it is more elegant)?
  • Review overall correctness

Here is a link to a list of Armstrong Numbers for verifying the outputs.

Please note that there is a follow up question.

asked Jul 13, 2016 at 4:45
\$\endgroup\$
1

1 Answer 1

3
\$\begingroup\$

Integer.toString(n).length() can be assigned to its own variable.

If you wanted to stream the while loop, I suppose you could split a toString() version of the number via toCharArray() and then calculate the value for each digit individually, then summing the result via the sum function.

I don't know whether that'd qualify as "more elegant", though. You would get rid of c and temp as variables by doing that.

answered Jul 13, 2016 at 10:01
\$\endgroup\$
2
  • \$\begingroup\$ Made changes as per your suggestion. Should I share it as an update to the question? \$\endgroup\$ Commented Jul 13, 2016 at 10:25
  • \$\begingroup\$ Follow up question: codereview.stackexchange.com/q/134734/104662 \$\endgroup\$ Commented Jul 13, 2016 at 11:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.