Skip to content

Instantly share code, notes, and snippets.

@matsub
Last active August 29, 2015 14:14
Show Gist options
  • Save matsub/9431d6f32b6b30a1da6c to your computer and use it in GitHub Desktop.
Save matsub/9431d6f32b6b30a1da6c to your computer and use it in GitHub Desktop.
# famous
def gcd(a, b):
if b:
return gcd(b, a%b)
return a
# non-recursive
def Gcd(a, b):
while b:
a, b = b, a%b
return a
# short
def GCD(a, b):
return gcd(b, a%b) if b else a
# Z-Combinator
Z = lambda f: (lambda x: f(lambda y: x(x)(y)))(lambda x: f(lambda y: x(x)(y)))
Zgcd = lambda f: (lambda a: (lambda b: f(b)(a%b) if b else a))
'''
>>> gcd(12, 64)
4
>>> GCD(24, 64)
8
>>> Z(Zgcd)(12)(64)
4
>>> Z(Zgcd)(24)(64)
8
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment