Was fiddling with java-8; 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.
-
\$\begingroup\$ Follow up question: codereview.stackexchange.com/q/134734/104662 \$\endgroup\$Bilesh Ganguly– Bilesh Ganguly2016年07月13日 11:03:09 +00:00Commented Jul 13, 2016 at 11:03
1 Answer 1
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.
-
\$\begingroup\$ Made changes as per your suggestion. Should I share it as an update to the question? \$\endgroup\$Bilesh Ganguly– Bilesh Ganguly2016年07月13日 10:25:57 +00:00Commented Jul 13, 2016 at 10:25
-
\$\begingroup\$ Follow up question: codereview.stackexchange.com/q/134734/104662 \$\endgroup\$Bilesh Ganguly– Bilesh Ganguly2016年07月13日 11:03:23 +00:00Commented Jul 13, 2016 at 11:03