How to calculate the GCD (greatest common divisor) of two numbers in Python

5 Answers

0 votes
import math

a = 12
b = 20

gcd = math.gcd(a, b)
 
print("The GCD (greatest common divisor) of ", a, " and ", b, " is: ", gcd)
  
  
  
  
'''
run:
  
The GCD (greatest common divisor) of  12  and  20  is:  4

'''

 



answered May 29, 2017 by avibootz
edited Aug 9, 2022 by avibootz
0 votes
a = 12
b = 20
i = a if a < b else b

while i <= a and i <= b:
    if a % i == 0 and b % i == 0:
        gcd = i
        break
    i -= 1

print("The GCD (greatest common divisor) of ", a, " and ", b, " is: ", gcd)
 



 
'''
run:
 
The GCD (greatest common divisor) of  12  and  20  is:  4
 
'''

 



answered May 29, 2017 by avibootz
edited Aug 9, 2022 by avibootz
0 votes
def gcd(a, b):
    return a if b == 0 else gcd(b, a % b)


x = 12
y = 20

print("The GCD (greatest common divisor) of ", x, " and ", y, " is: ", gcd(x, y))
 



 
'''
run:
 
The GCD (greatest common divisor) of  12  and  20  is:  4
 
'''

 



answered May 29, 2017 by avibootz
edited Aug 9, 2022 by avibootz
0 votes
a = 12
b = 20
i = 1
 
while i <= a and i <= b:
    if a % i == 0 and b % i == 0:
        gcd = i
    i += 1
 
print("The GCD (greatest common divisor) of ", a, " and ", b, " is: ", gcd)
  
  
  
  
  
'''
run:
  
The GCD (greatest common divisor) of  12  and  20  is:  4
  
'''

 



answered Aug 9, 2022 by avibootz
0 votes
import numpy as np
 
a = 12
b = 20
 
gcd = np.gcd(a, b)
  
print("The GCD (greatest common divisor) of ", a, " and ", b, " is: ", gcd)
   
   
   
   
'''
run:
   
The GCD (greatest common divisor) of  12  and  20  is:  4
 
'''

 



answered Feb 26, 2023 by avibootz
...