IntStream

Difference of Squares
Difference of Squares in Java
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.

Note

The difference between rangeClosed() and range() 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.

27th Nov 2024 · Found it useful?