how the complexity of gcd is logn ?please explain and also n here represents which of the two numbers the graeter one or the smaller one?
Complexity of gcd
// Function to return
// gcd of a and b
int
gcd(
int
a,
int
b)
{
if
(a == 0)
return
b;
return
gcd(b % a, a);
}
Time Complexity: O(Log min(a, b))
but how is it log n please also tell this?
At every step, there are two cases
- b >= a / 2, then a, b = b, a % b will make b at most half of its previous value
- b < a / 2, then a, b = b, a % b will make a at most half of its previous value, since b is less than a / 2
So at every step, the algorithm will reduce at least one number to at least half less. In at most O(log2a)+O(log2b)O(log2a)+O(log2b) step, this will be reduced to the simple cases. Which yield an O(log2n)O(log2n) algorithm, where n is the upper limit of a and b.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.