 GFG App
Open App Browser
Continue

# Javascript Program for Products of ranges in an array

Given an array A[] of size N. Solve Q queries. Find the product in the range [L, R] under modulo P ( P is Prime).

Examples:

```Input : A[] = {1, 2, 3, 4, 5, 6}
L = 2, R = 5, P = 229
Output : 120

Input : A[] = {1, 2, 3, 4, 5, 6},
L = 2, R = 5, P = 113
Output : 7 ```

Brute Force
For each of the queries, traverse each element in the range [L, R] and calculate the product under modulo P. This will answer each query in O(N).

## Javascript

 ``

Output :

```120
6```

Efficient Using Modular Multiplicative Inverse:
As P is prime, we can use Modular Multiplicative Inverse. Using dynamic programming, we can calculate a pre-product array under modulo P such that the value at index i contains the product in the range [0, i]. Similarly, we can calculate the pre-inverse product under modulo P. Now each query can be answered in O(1).
The inverse product array contains the inverse product in the range [0, i] at index i. So, for the query [L, R], the answer will be Product[R]*InverseProduct[L-1]
Note: We can not calculate the answer as Product[R]/Product[L-1] because the product is calculated under modulo P. If we do not calculate the product under modulo P there is always a possibility of overflow.

## Javascript

 ``

Output :

```7
6```

Please refer complete article on Products of ranges in an array for more details!

My Personal Notes arrow_drop_up