0

I am trying to find the GCD of 3 numbers but have been unable to get around much success till now. I am using the following code

def gcd(a, b,c):
    if sum(np.array(list([a,b,c]))%min(a,b,c))==0:
        return min(a,b,c)
    else:
        x = np.array(list([a,b,c]))%min(a,b,c)
        if sum((list([x]))%min(x))==0:
            return min(x)

When I run this on an example say gcd(21,45,60), it gives me the below error

C:\Users\mmt8091\Anaconda3\lib\site-packages\ipykernel_launcher.py:6: RuntimeWarning: divide by zero encountered in remainder

What am i doing wrong here? Have been unable to find any other solutions on net as well. Please help

Andy K
  • 4,944
  • 10
  • 53
  • 82
Akshit
  • 123
  • 1
  • 8
  • You can find the explanation to same kind of problem here: 1) https://stackoverflow.com/questions/16628088/euclidean-algorithm-gcd-with-multiple-numbers 2) https://www.geeksforgeeks.org/python-program-for-gcd-of-more-than-two-or-array-numbers/ – Ananth Apr 19 '20 at 07:29
  • Does this answer your question? [Euclidean algorithm (GCD) with multiple numbers?](https://stackoverflow.com/questions/16628088/euclidean-algorithm-gcd-with-multiple-numbers) – Ananth Apr 19 '20 at 07:31
  • 3
    If you find it easier you could implement `gcd(a, b)`, and then let `gcd3(a, b, c) = gcd(gcd(a, b), c)`. – Erik André Apr 19 '20 at 07:32
  • 1
    Erik +1, or nth gcd via: https://www.geeksforgeeks.org/args-kwargs-python/ – A. Abramov Apr 19 '20 at 07:34
  • Thanks @Erik, I have been trying to do that, but how can i let gcd3(a, b, c) = gcd(gcd(a, b), c)? Sorry I am new to Python – Akshit Apr 19 '20 at 07:47
  • "What am i doing wrong here?" - almost everything. It's not some singular mistake causing things to go wrong. Your function has the right number of arguments, and the `%` operator and comparison to 0 are things involved in a GCD computation, but pretty much everything else in this code is completely misguided. – user2357112 Apr 19 '20 at 08:03
  • The `list` calls are redundant, the `sum`s and `min`s don't really have anything to do with the goal, and the function doesn't do anything to find divisors of the inputs. `min(x)` is always going to be 0, so it can't be sensibly placed on the right side of a `%` operation, and even if you could do that without error, the function would run off the end without returning in the `!= 0` case. – user2357112 Apr 19 '20 at 08:19

1 Answers1

2

You do not need np.

Try this:

def gcd(*args):
    a, b, *c = args
    a, b = min(a, b), max(a, b)
    gcd1 = b if not a else gcd(b % a, a)
    for i in c:
        gcd1 = gcd(gcd1, i)
    return gcd1


print(gcd(21, 45, 60))
sureshvv
  • 4,234
  • 1
  • 26
  • 32