Given an array, I want to count the number of subarrays (contiguous) who's product when taken will not be divisible by k.
Eg. Let A = [1, 2, 3, 4, 5, 6]
and K = 2
Then the number of subarrays such that the product is not divisible by K is 2:
{1}
{3}
{5}
Rest of them are all divisible by 2.
{1, 2}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6}
{2}
{2, 3}
{2, 3, 4}
{2, 3, 4, 5} etc..
I tried first calculating the total number of subarrays (n)(n+1)/2 and then subtracting the number of subarrays that are divisible by k by using mod but it doesn't work. How do I get around this one?
This calculates (wrongly) number of subarrays who's product is divisible by K:
int curr = 1;
int x = 0;
for (int i = 0; i < a.length; i++) {
curr = curr * a[i] % k;
if (curr == 0) {
curr = 1;
if (x > 0)
ans = ans.subtract(NumberUtils.nChooseR(x + 1, 2));
if (a[i] % k != 0) {
x = 1;
} else {
x = 0;
}
} else {
x++;
}
}
if (x != 0) {
ans = ans.subtract(NumberUtils.nChooseR(x + 1, 2));
}
return ans;
A slightly related question is this one but it involves addition so it cannot be applied here.
Edit : constraints on array size is 10^5 and on array elements is 10^9. Hence, I'm looking for solution in linear or linearithmic time