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 - lowat the top-level call.E.g. take
N=2^Kfor convenience. You are recursingKlevels deep before you hit the case wherelow==high. At each level, you have2^(K-1)calls. They add up to a total ofN - 1calls (1 + 2 + 4 + ... + 64 = 127).For general
Nthe 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.