Greatest Common Divisor
Greatest Common Divisor or commonly known as gcd
of two integers is greatest common integer that completely divides both of them.
means d divides a
Euclidean Algorithm
-
Problem :- Find
Naive way of doing this would be to just iterate over all integers in reverse order until you find an integer that divides both and .
Time complexity
-
-
Intuition behind
Euclidean Algorithm
to solve this problem efficiently
Let's say is some integer that divides both and . Then we can prove also divides .
Proof -
Let's build further intuition on thisproof
. Let be represented as is and is .
Now we can prove that also divides . Here is theproof
-
-
-
-
-
-
-
Let's see why this helps :
If a number divides both and then it must also divide because
So -
Example
-
Let's see a concrete example with and :
-
(First divide by )
-
(Then divide by )
-
(Finally divide by )
-
At each step, we're reducing the problem to finding gcd of smaller numbers
Why this algorithm works ?
-
Each remainder is strictly smaller than the previous divisor
-
The remainders keep getting smaller
-
They can't go below zero
-
So the process must eventually terminate when we get remainder
-
The last non-zero remainder is our gcd
-
-
Recursive Definition (Euclidean Algorithm)
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b , a % b);
}
Time Complexity