Swift Program to Find LCM

1. Introduction

The Least Common Multiple (LCM) of two integers is the smallest integer that is divisible by both numbers. In this guide, we will explore a Swift program to find the LCM of two numbers using the formula: (a * b) / gcd(a, b), where gcd is the Greatest Common Divisor.

2. Program Overview

We'll begin by defining two numbers. To find the LCM, we will first compute the GCD (using Euclid's algorithm) and then use the aforementioned formula.

3. Code Program

// Define the two numbers
let num1 = 15
let num2 = 20

// Function to compute the GCD of two numbers
func gcd(_ a: Int, _ b: Int) -> Int {
    if b == 0 {
        return a
    } else {
        return gcd(b, a % b)
    }
}

// Function to compute the LCM of two numbers
func lcm(_ a: Int, _ b: Int) -> Int {
    return (a * b) / gcd(a, b)
}

let result = lcm(num1, num2)
print("LCM of \(num1) and \(num2) is: \(result)")

Output:

LCM of 15 and 20 is: 60

4. Step By Step Explanation

1. let num1 = 15 and let num2 = 20: These are the two numbers for which we want to find the LCM.

2. The function gcd calculates the Greatest Common Divisor of two numbers using Euclid's algorithm. This algorithm works based on the principle that the GCD of two numbers also divides their difference.

3. The function lcm calculates the Least Common Multiple using the formula: (a * b) / gcd(a, b). The formula stems from the relationship between the GCD and the LCM of two numbers.

4. We then call the lcm function with our two numbers as arguments and print the result.

This program provides an efficient way to compute the LCM, especially for large numbers, by first calculating the GCD.


Comments