Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 48 / 68

Finding the GCD and LCM (the Euclidean Algorithm)

In this lesson you will find the greatest common divisor and least common multiple with the Euclidean algorithm, getting hands-on with recursion. This is for anyone searching for "PHP how to find the GCD".

The Euclidean algorithm is an ancient, efficient way to find the greatest common divisor (GCD) of two numbers. You repeat "divide the larger by the smaller and carry on with the remainder" until the remainder reaches zero.

The sample code has gcdFunc($a, $b) call itself as gcdFunc($b, $a % $b) until $b === 0. The least common multiple (LCM) then comes from ($a * $b) / gcdFunc($a, $b) - notice how the two algorithms connect.

A common stumbling block for beginners is why that formula gives the LCM at all. Knowing the mathematical relationship - the product of the two numbers divided by their GCD - turns rote memorisation into real understanding.

It is a good exercise that builds algorithmic intuition, and a very popular subject for practising recursion. It is a famous algorithm that packs in the fundamentals of both mathematics and programming.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)