Given an array, I want to count the number of subarrays (adjacent) that, when executed, will not be divided 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}
The rest of them are divided 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 to calculate the total number of subarrays (n) (n + 1) / 2 first and then subtract the number of subarrays that are divisible by k using mod, but that does not work. How do I get around this?
This calculates (erroneously) the number of subarrays whose product is divided 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;
Bit related question this , but it includes the addition, so it can not be applied here.
: 10 ^ 5, - 10 ^ 9. ,