Ad space (banner)
๐ŸฆSwift Lessons
Lesson 48 / 68

Finding the GCD and LCM (the Euclidean Algorithm)

In this lesson you will learn how to find the greatest common divisor and least common multiple in Swift with the Euclidean algorithm, and understand a mathematical algorithm built on recursion. This is for anyone searching for "Swift GCD LCM implementation".

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 expresses the recursion in a single line with a ternary operator: b == 0 ? a : gcd(b, a % b). From the relationship a * b / gcd(a, b), lcm() then reuses that result to find the least common multiple.

A common stumbling block for beginners is not knowing the relationship between the GCD and the LCM. Once you have the GCD, one multiplication and one division give you the LCM.

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

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

๐Ÿงช This site can't compile or run Swift 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)