To find the greatest common divisor (GCD) of two numbers in Swift, we can use the Euclidean algorithm.
main.swift150 chars9 lines
Here, we define a recursive function gcd
that takes two integers a
and b
as parameters. We first find the remainder of a
divided by b
using the modulo operator %
. If the remainder is zero, then the GCD is b
, and we return it. Otherwise, we recursively call the gcd
function with b
and the remainder as the new parameters. This continues until we reach a point where the remainder is zero and we can return the GCD.
We can call the gcd
function with two numbers like this:
main.swift122 chars5 lines
This will output GCD of 24 and 36 is 12
, which is the correct answer.
gistlibby LogSnag