I have an array of n
positive integers. I want to calculate a list of all contiguous subarray products of size k
modulo p
. For instance for the following array:
a = [3, 12, 5, 2, 3, 7, 4, 3]
with k = 3
and p = 12
, the ordered list of all k
-sized contiguous subarray products will be:
k_products = [180, 120, 30, 42, 84, 84]
and modulo p
we have:
k_products_p = [0, 0, 6, 6, 0, 0]
we can easily compute k_products
using a sliding window. All we have to do is to compute the product for the first k
-sized subarray and then compute the next elements of k_product
using the following formula:
k_product[i] = k_product[i - 1] * a[i + k] / a[i - 1]
and after forming the whole list, we can compute k_product[i] % p
for each i
to get k_product_p
. That's it. O(n)
complexity is pretty good.
But if the elements of a[i]
are big, the elements of k_product may overflow, and thus we cannot compute k_product_p
. Plus, we cannot, for example do the following:
k_product[i] = ((k_product[i - 1] % p) * (a[i + k] % p) / (a[i - 1] % p)) % p // incorrect
So is there a fast algorithm to do this? Note that p
is not necessarily prime and it is also not necessarily coprime to the elements of a
.
Edit: As mentioned in the comments, there will be no overflow in python, but working with very big numbers will be time-consuming.