CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

| Download
Views: 103
############################################## # Problem 0 - Euclidean Algorithm ##############################################
def gcd_ea(a,b): """ This function returns the Greatest Common Divisor of a and b. """ x = abs(a) y = abs(b) while (y != 0): #Can speed things up using y != 0 vs y > 0 # print (x,y) r = mod(x,y) #Is faster faster with x%y x = y y = r return x #Return gcd(a,b)
import time
t = time.time() #Start Time gcd_ea(8675309,3892394) dt = time.time() - t #Difference in Time = End Time - Start Time print dt
1 0.000687837600708
t = time.time() #Start Time gcd_ea(31313,519) dt = time.time() - t #Difference in Time = End Time - Start Time print dt
173 0.00163507461548
############################################## # Problem 1.c - Extended Euclidean Algorithm ##############################################
def gcd_eea(a,b): u = 1 g = a y = b x = 0 while (y != 0): q = g//y #Faster with g//y vs floor(g/y) t = g%y #Is faster faster with % s = u - q*x u = x g = y x = s y = t v = (g - a*u)/b return (g,u,v)
gcd_eea(31313,519) gcd_eea(167181,163961) gcd_eea(8675309,3892394)
(173, 1, -60) (7, -4430, 4517) (1, -843845, 1880749)
import time
t = time.time() gcd_eea(8675309,3892394) dt = time.time() - t dt
(1, -843845, 1880749) 0.00080108642578125
############################################## # Problem 1.d - Extended Euclidean Algorithm ##############################################
def gcd_eea_posu(a,b): u = 1 g = a y = b x = 0 while (y != 0): q = floor(g/y) #q = g//y #Faster with g//y vs floor(g/y) t = g%y #Is faster faster with % s = u - q*x u = x g = y x = s y = t v = (g - a*u)/b while (u < 0): u = u + b/g v = v - a/g return (g,u,v)
t = time.time() gcd_eea_posu(8675309,3892394) dt = time.time() - t dt
(1, 3048549, -6794560) 0.0007898807525634766
gcd_eea_posu(31313,519) gcd_eea_posu(167181,163961) gcd_eea_posu(8675309,3892394)
(173, 1, -60) (7, 18993, -19366) (1, 3048549, -6794560)