Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,959 questions

51,901 answers

573 users

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
...