2

I have created the following function, which takes two Integers as parameters and computes the GCD of them:

func getGCD(_ num1: Int, _ num2: Int) -> Int {

    let remainder = num1 % num2
    if remainder != 0 {
        return gcd(num2, remainder)
    } else {
        return num2
    }
}

NOTE: I want to use Recursivity.

Question 1: Is there any way to make this function more efficient?

Question 2: How can I use this function for an Array of type [Int]?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • This place is not meant to give you a solution to your homework – Simon Feb 04 '17 at 19:49
  • This is just an algorithm question. Language is effectively irrelevant. Good discussion here: http://stackoverflow.com/questions/16628088/euclidean-algorithm-gcd-with-multiple-numbers – matt Feb 04 '17 at 19:50
  • Your code doesn't work anyway, because `getGCD` and `gcd` are two different names. – matt Feb 04 '17 at 19:55

2 Answers2

5

Once you have a function gcd (or getGCD) working for two integers, the following will work for an array arr of integers:

let result = arr.reduce(0) {gcd($0,$1)}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • So does mine, actually. The problem lies in your `getGCD`, which is totally broken in the form you have shown it in any case. – matt Feb 04 '17 at 20:00
  • oh, yes sorry. It is my fault. –  Feb 04 '17 at 20:00
  • No, now that I have read both the answers twice, it is clear that your answer is better, because it is very efficient compared to the other one, and my function was messed up, anyways. Thanks for your time! –  Feb 04 '17 at 20:04
  • you could even write `arr.reduce(0, gcd)` – ramzesenok Dec 13 '20 at 12:14
  • @ramzesenok nice one! – matt Nov 13 '22 at 02:06
0

First of all, your function doesn't work for negative Integers, so a way to make it "more efficient" is to use abs(), to get the absolute value of the numbers:

func gcd(_ a: Int, _ b: Int) -> Int {
    let remainder = abs(a) % abs(b)
    if remainder != 0 {
        return gcd(abs(b), remainder)
    } else {
        return abs(b)
    }
}

Second Question - Working with arrays:

var numbers = [5,10]
var index = 0
var result = 0
if numbers.isEmpty{result=0}
else if numbers.count == 1{result = numbers[0]}
else{
    while index <= numbers.count-1{
        if index==0{
            result = gcd(numbers[index], numbers[index + 1])
            index+=2
        }
        else {
            result = gcd(result,numbers[index])
            index+=1
        }
    }

}
print(result) // prints 5
Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
  • Thank you for suggesting the function improvement! However, I have accepted Matt's answer since it is way more efficient –  Feb 04 '17 at 20:06