Search code examples
pythonpython-3.xgreatest-common-divisor

How to find the GCD/HCF of three numbers in Python3


I need a code to find the common prime factors of three numbers in Python 3

Whenever I run it shows me the wrong HCF / GCD.


Solution

  • Very simple.
    Write a function, that calculates gcd/lcm of two numbers.
    Then do something like this.

    gcd(a,b,c) = gcd(a, gcd(b,c))
    
     >>> def gcd(a,b):
    ...     if b == 0:
    ...             return a
    ...     else:
    ...             return gcd(b, a%b)
    ... 
    >>> gcd(3,5)
    1
    >>> gcd(10,5)
    5
    >>> gcd(10,15)
    5
    >>> gcd(5,gcd(10,15))
    5
    

    You can try by yourself, for lcm.