0

How can we find the HCF or GCD and LCM of two given numbers using swift?

4th Sep 2016, 10:16 AM
Ruchi Gupta
Ruchi Gupta - avatar
4 Antworten
+ 1
//I wrote two ways to do HCF or GCD // #1 func hcf(num1: Int, num2: Int) -> Int { var numA = num1 var numB = num2 while numA != 0 && numB != 0 { if numA >= numB { numA %= numB } else { numB %= numA } } return max(numA, numB) } hcf(num1: 175, num2: 50) // get 25 //#2 func gcd(num1: Int, num2: Int) -> Int { if num2 == 0 { return num1 }else { return gcd(num1: num2, num2: num1 % num2) } } gcd(num1: 175, num2: 50) //get 25 too // lcm * gcd = num1 * num2 func lcm(num1: Int, num2: Int) -> Int { return num1 * num2 / gcd(num1: num1, num2: num2) } lcm(num1: 175, num2: 50)
17th Sep 2016, 4:10 PM
Nplus Chang
Nplus Chang - avatar
0
Yes ofcourse
4th Sep 2016, 5:36 PM
Prashant
Prashant - avatar
0
Hi Ruchi Gupta Here it is in Swift 2.2 gcf , greatest common factor. func gcfof(inout m: Int, inout n: Int) { // used inout key to be able to modify the arguments while n != 0 { let remainder = m % n m = n n = remainder } print(m) } // Example var a = 120 var b = 16 print("The greatest common factor of \(a) and \(b) is", terminator: " ") gcfof(&a, n: &b) // & before the argument to tell to the compiler that I am changing this inputs /*Output The greatest common factor of 120 and 16 is 8*/
5th Sep 2016, 8:09 PM
Abdelkader Ait Assou
Abdelkader Ait Assou - avatar
0
For the least common factor use this formula: lcd(a, b) = (a*b) / gcfof(a, b) Dont forget to reset a and b between gcfof(a,b) and lcd(a,b) to what you set them before cause they are modified you call gcf function example: var a = 120 var b = 16 gcf(a,b) >>>>> 8 a = 120 b = 16 lcd(a, b) >>>> 240
5th Sep 2016, 9:52 PM
Abdelkader Ait Assou
Abdelkader Ait Assou - avatar