Visit the difference-of-squares exercise on Exercism to read the full instructions and download the exercise files.
Dig Deeper
IntStream
IntStream
import java.util.stream.IntStream;
class DifferenceOfSquaresCalculator {
int computeSquareOfSumTo(int input) {
int sum = IntStream.rangeClosed(1, input).sum();
return sum * sum;
}
int computeSumOfSquaresTo(int input) {
return IntStream.rangeClosed(1, input)
.map(num -> num * num)
.sum();
}
int computeDifferenceOfSquares(int input) {
return computeSquareOfSumTo(input) - computeSumOfSquaresTo(input);
}
}
This solution iterates using the rangeClosed() method of the IntStream class.
The difference between `rangeClosed()` and [`range()`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#range-int-int-)
is that the ending bound is _inclusive_ for `rangeClosed()` and _exclusive_ for `range()`.
So, `IntStream.range(1, 10)` iterates from `1` up to but not including `10`,
and `IntStream.rangeClosed(1, 10)` iterates from `1` through `10`.
In computeSquareOfSumTo, the numbers are added with the sum() method.
The sum of the numbers is then multiplied by itself to get the square of the summed numbers.
Note it avoids using Math.pow() here,
since multiplying a value by itself is usually more efficient than type-casting from intto double back to int.
In computeSumOfSquaresTo, each number is squared by multiplying it by itself inside the map() method.
Again, the number is multiplied by itself instead of using pow() and converting the double result back into an int.
All of the squared numbers are added using the sum() method.
class DifferenceOfSquaresCalculator {
int computeSquareOfSumTo(int input) {
int sum = (input * (input + 1)) / 2;
return sum * sum;
}
int computeSumOfSquaresTo(int input) {
return (input * (input + 1) * ((input * 2) + 1)) / 6;
}
int computeDifferenceOfSquares(int input) {
return computeSquareOfSumTo(input) - computeSumOfSquaresTo(input);
}
}
In this solution a formula is used to solve the computeSquareOfSumTo and computeSumOfSquaresTo functions.
At the time of this writing the instructions state:
You are not expected to discover an efficient solution to this yourself from first principles;
research is allowed, indeed, encouraged. Finding the best algorithm for the problem is a key skill in software engineering.
It is fine to search for an algorithm on the internet.
This is also sometimes referred to as “Google is your friend”, although you don’t have to search with Google.
It is okay if you don’t understand how the algorithm works.
What is important is that it obviously is not introducing malware and that it passes the tests.
Note that this avoids using Math.pow() in computeSquareOfSumTo,
since multiplying a value by itself is usually more efficient than type-casting from intto double back to int.
Source: Exercism java/difference-of-squares