JetBrains Academy: Reduction methods - Kamil-Jankowski/Learning-JAVA GitHub Wiki

JetBrains Academy: Reduction methods

Calculating factorials:

Many java developers wrote methods to calculate a factorial value using a recursive or iterative algorithm. It's time to do it with streams.

The factorial of n is calculated by the product of integer number from 1 to n (inclusive). The factorial of 0 is equal to 1.

/**
 * Calculates the factorial of the given number n
 *
 * @param n >= 0
 *
 * @return factorial value
 */
 
public static long factorial(long n) {
    return LongStream.rangeClosed(1, n).reduce(1, (factorial, number) -> factorial * number);
}

Range quadratic sum:

Implement the provided method rangeQuadraticSum that takes range borders (fromIncl - inclusive, toExcl - exclusive) and calculates the sum of the squares of the elements which belong to the range.

Please, use streams to solve the problem.

public static long rangeQuadraticSum(int fromIncl, int toExcl) {
    return LongStream.range(fromIncl, toExcl).reduce(0, (sumOfSquares, number) -> sumOfSquares + number * number);
}

Sum of divisors:

For a given range from A to B both inclusive, count sum of numbers that are only divisible by N or M. Use streams to solve the problem.

For example, for range from 10 to 20 and N = 2, M = 3, there are 6 numbers that are divisible by N or M - 10, 12, 14, 15, 16, 18, 20. And their sum equals 105.

Input contains a single line with four numbers - A, B, N, M.

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int lowerBound = scanner.nextInt();
        int upperBound = scanner.nextInt();
        int firstDivider = scanner.nextInt();
        int secondDivider = scanner.nextInt();
        
        long sumOfDivisors = IntStream.rangeClosed(lowerBound, upperBound)
                                      .filter(number -> number % firstDivider == 0 || number % secondDivider == 0)
                                      .sum();
        
        System.out.println(sumOfDivisors);
    }
}