int gcd(int a, int b)
{
while(a!=b)
{
if(a > b)
a = a - b;
else
b = b - a;
}
return a;
}
What is the time complexity of this algorithm? Can someone provide a detailed explanation?
int gcd(int a, int b)
{
while(a!=b)
{
if(a > b)
a = a - b;
else
b = b - a;
}
return a;
}
What is the time complexity of this algorithm? Can someone provide a detailed explanation?
For Euclid Algorithm by Subtraction,
a
andb
are positive integers.The worst case scenario is if
a = n
andb = 1
. Then, it will taken - 1
steps to calculate the GCD. Hence, the time complexity is O(max(a,b)) or O(n) (if it's calculated in regards to the number of iterations).By the way, you should also fix your function so that it validates whether
a
andb
are really positive integer numbers. Or even better, you could change your return and parameter types tounsigned long
orunsigned int
or similar and, as suggested by @templatetypedef, handle cases fora = 0
orb = 0
separately.