YogeshChauhan.com
How to find the HCF or GCD and LCM of two given numbers using Swift?
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.

dreamhost

Leave a Reply

Most Read

#1 How to set opacity or transparency using CSS? #2 Pagination in CSS with multiple examples #3 How to check if radio button is checked or not using JavaScript? #4 How to make HTML form interactive and using CSS? #5 How to uninstall Cocoapods from the Mac OS? #6 How to add Read More Read Less Button using JavaScript?



Recently Posted

Feb 24 How to modify the latest post array using get_posts() in WordPress? Feb 22 WordPress: How to get ACF field values from another post? Feb 22 WordPress: How to print ACF repeater field values? Feb 22 WordPress: How to print ACF array field values? Feb 21 WordPress: How to get field values in Advanced Custom Fields? Feb 21 WordPress: How to add a Search Icon in Menus with toggle effect using jQuery?



You might also like these

Some SQL LIKE Operators We Need to Keep in MindSQL/MySQLLearn how to give a temporary name to a column or to a table using SQL AliasesSQL/MySQLHow to create ‘share on LinkedIn’ link using just HTML?HTMLAdvanced Array Methods in JavaScript (with examples)JavaScriptHow to Use ROLLUP Operator in SQL and MySQL?SQL/MySQLSQL Left JoinSQL/MySQL