A friend of mine posted his Groovy solution to Project Euler Problem #6, so I figured I’d post a Java solution. Here it is using Iterate (note that the second parameter of range()
is the exclusive upper bound):
square().apply(each(range(1, 101)).reduce(sum())) - each(range(1, 101)).map(square()).reduce(sum());
And a nicer version using an upcoming release of Iterate:
square().apply(range(1, 101).reduce(sum())) - range(1, 101).map(square()).reduce(sum());
And here’s a straight Java version for comparison:
int sum = 0;
int sumOfSquares = 0;
for(int i=1; i<=100; i++) {
sum += i;
sumOfSquares += i * i;
}
int answer = (sum * sum) - sumOfSquares;