int gcd(int n, int m)
{
if (n%m ==0) return m;
if (n < m) swap(n, m);
while (m > 0)
{
n = n%m;
swap(n, m);
}
return n;
}
How is the time complexity O(logn) here ?
int gcd(int n, int m)
{
if (n%m ==0) return m;
if (n < m) swap(n, m);
while (m > 0)
{
n = n%m;
swap(n, m);
}
return n;
}
How is the time complexity O(logn) here ?
Hi @abhishekjohri98,
This is because in each step of n=n%m the number n is divided by m and hence the tree that is formed is having height log(n) hence the algorithm will run in O(log(n)) time .Moreover your algorithm might be wrong as m>0 might end up in infinite loop so if this algorithm does not end up in infinite loop then the running time will be O(log(n)).