Yogesh Chauhan's Blog

How to find the HCF or GCD and LCM of two given numbers using Swift?

in Swift on March 5, 2020

What is GCD?

The greatest common divisor (gcd) of two or more integers is the largest positive integer that divides each of the integers. For example, the gcd of 8 and 12 is 4. It is also known as the greatest common factor (gcf), highest common factor (hcf), greatest common measure (gcm), or highest common divisor.

What is LCM?

The least common multiple, lowest common multiple, or smallest common multiple of two integers a and b, usually denoted by LCM(a, b), is the smallest positive integer that is divisible by both a and b.

What is LCD?

The lowest common denominator or least common denominator (abbreviated LCD) is the lowest common multiple of the denominators of a set of fractions.

Regarding our problem, we can make functions to calculate GCD and LCM.


func gcd(numerator: Int, denominator: Int) -> Int
  {
    if (numerator == 0) {
    return denominator;
  } else {
    return gcd(numerator: denominator % numerator, denominator:numerator);
    }
  }

func lcm(numerator: Int, denominator: Int) -> Int {
  return (numerator * denominator) / gcd(numerator: numerator, denominator: denominator);
}
           
let lcd = lcm(numerator: f1.denominator, denominator: f2.denominator)

//use it in further calculation

Now to add, multiply, divide or subtract, all we need to do is to pass the numerator and denominator.


amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS? #Aug 1 What is Zdog? #Aug 1 How to add before after image effect using pure CSS? #Jul 31 Add animation to your skills bar using CSS #Jul 31 Use SwiperJS to create mobile touch sliders fast
You might also like these
How to check if checkbox is checked or not using JavaScript?JavaScriptWhat’s a Closure in JavaScript?JavaScriptSolution to Could not cast value of type ‘NSTaggedPointerString’ to ‘NSNumber’SwiftValues and Types Basics in JavaScriptJavaScriptSome EASY-to-Understand CSS media query examplesCSSHow to select an element using its ID without the high specificity of the ID selector?CSS