Exercise 6
Exercise:
Write a Java program that uses parallelism to calculate the factorial of a given number using the Fork/Join framework. The program should take an integer input from the user and then split the calculation into smaller subproblems that are executed concurrently in parallel.
Steps:
- Create a class `FactorialTask` that extends `RecursiveTask<Long>`.
- In the `FactorialTask` class, define an integer `n` as an instance variable to store the number for which factorial is to be calculated.
- Implement the `compute()` method in `FactorialTask` to calculate the factorial of the given number. If `n` is less than or equal to 1, return 1; otherwise, split the problem into two halves and create two subtasks to compute the factorial of each half concurrently.
- In the `main()` method of the main class, take an integer input from the user for which the factorial is to be calculated.
- Create a ForkJoinPool and create an instance of `FactorialTask` with the input number as `n`. Invoke the task using the ForkJoinPool.
- Print the final result, which is the factorial of the given number.