Euclid’s algorithm is used to find GCD of two numbers.
There are mainly two versions of algorithm.
Version 1 (Using subtraction)
Version 2 (Using modulo operator)
Which of the above two is more efficient?
Version 1 can take linear time to find the GCD, consider the situation when one of the given numbers is much bigger than the other. Version 2 is obviously more efficient as there are less recursive calls and takes logarithmic time.
Consider a situation where modulo operator is not allowed, can we optimize version 1 to work faster?
Below are some important observations. The idea is to use bitwise operators. We can find x/2 using x>>1. We can check whether x is odd or even using x&1.
gcd(a, b) = 2*gcd(a/2, b/2) if both a and b are even.
gcd(a, b) = gcd(a/2, b) if a is even and b is odd.
gcd(a, b) = gcd(a, b/2) if a is odd and b is even.
Below is C++ implementation.
This article is compiled by Shivam Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Minimize the value of N by applying the given operations
- Maximize the Sum of the given array using given operations
- ML | Linear Algebra Operations
- Operations on Sparse Matrices
- Print N distinct numbers following the given operations
- Making three numbers equal with the given operations
- Reduce a number to 1 by performing given operations | Set 2
- Alternate XOR operations on sorted array
- Reduce N to 1 with minimum number of given operations
- Minimum bitwise operations to convert given a into b.
- Implement *, - and / operations using only + arithmetic operator
- Convert N to M with given operations using dynamic programming
- Bitwise Operations on Digits of a Number
- Find maximum operations to reduce N to 1
- Minimize operations required to obtain N
- Bitwise operations on Subarrays of size K
- Min operations to reduce N to 1 by multiplying by A or dividing by B
- Online Queries for GCD of array after divide operations
- Minimum operations to make two numbers equal
- Minimum operations required to change the array such that |arr[i] - M| <= 1