i am trying to count total number of subarrays which are divisibleby a given number .
#include <iostream>
using namespace std;
int countsubarray(int array[], int n, int k)
{
int count = 0;
int i, j, mul;
for (i = 0; i < n; i++)
{
if (array[i]%k==0)
count++;
mul = array[i];
for (j = i + 1; j < n; j++)
{
mul = mul * array[j];
if (mul%k==0)
count++;
}
}
return count;
}
int main()
{
int n,k;
cin>>n>>k;
int array[n],i;
for(i=0;i<n;++i)
{
cin>>array[i];
}
int count = countsubarray(array, n, k);
cout << count << "\n";
}
Hmmm … odd. I can’t immediately see anything that could cause a crash, and for me (after adding the missing #includes) it prints out the number 18:
Dunno then - the only thing I can think of is that the input is not being provided correctly, and n and k are keeping their undefined values (though I thought C++11 was supposed to set them to 0 in the case of an unsuccessful formatted extraction?).
Can you add:
cout << "n: " << n << " k: " << k << endl;
under the line:
cin>>n>>k;
and re-run as you have been doing with the same test input and post the output?
Also, what precisely are you trying to do? Are you trying to find the “subarray having product equal to a given number”, as you state here, or “count total number of subarrays which are divisible by a given number” as you state in the original post? The two are not equivalent.