Sunday, 14 November 2021

Factorial of any number in Java 8 - using reduction

Reduction - will reduce a stream of values to a result by using an identity (may be an initial value) and a function that will be applied internally on that stream. This processing may not be sequentially, its parallel stream.

import java.util.stream.LongStream;


public class Factorial {
public static void main(String[] args) {
    System.out.println(facto(5));
}

public static int facto(int n){
return IntStream.rangeClosed(1, n)
.reduce(1, (int a, int b) -> a * b);
}
}
we can either use LongStream or IntStream. 
LongStream.rangeClosed(1, n) gives stream of values from 1 to n, 
n is included here.
if you want to exclude nth value, 
you can use
LongStream.range(1, n) gives stream of values from 1 to n-1.
reduce function will apply a function a*b with 1 as initial value
 (also known as identity)
Its the similar operation as the following code.
long result = identity;
* for (long element : this stream)
* result = accumulator.applyAsLong(result, element)
* return result;
But the above code performs the same operation in sequential manner, 
but the reduce will apply the function in parallel form.

No comments:

Post a Comment