int multiply(int a[],int low,int high,int modulus)
{
if(low==high)
return (a[low]);
else
{
int mid = (low+high)/2;
int x = multiply(a, low, mid, modulus) % modulus;
int y = multiply(a, mid+1, high, modulus) % modulus;
return ((x*y) % modulus);
}
}
Is its time complexity O(log n) or it is O(n) ?
Please help me.
You are making
O(N)
calls tomultiply
, whereN == high - low
at the top-level call.E.g. take
N=2^K
for convenience. You are recursingK
levels deep before you hit the case wherelow==high
. At each level, you have2^(K-1)
calls. They add up to a total ofN - 1
calls (1 + 2 + 4 + ... + 64 = 127).For general
N
the scaling behavior is the same, which you can prove using Case 1 of the Master Theorem based on the recursion relationT(N) = 2 T (N / 2)
of your function.