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,
aandbare positive integers.The worst case scenario is if
a = nandb = 1. Then, it will taken - 1steps 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
aandbare really positive integer numbers. Or even better, you could change your return and parameter types tounsigned longorunsigned intor similar and, as suggested by @templatetypedef, handle cases fora = 0orb = 0separately.