Skip to content

Instantly share code, notes, and snippets.

@jordi-petit
Last active April 26, 2018 07:32
Show Gist options
  • Select an option

  • Save jordi-petit/815f76ebdad761ded993f0f7c1e58884 to your computer and use it in GitHub Desktop.

Select an option

Save jordi-petit/815f76ebdad761ded993f0f7c1e58884 to your computer and use it in GitHub Desktop.
2017-12-19 Exponenciació ràpida
# retorna x^n, amb n natural
def exp(x, n):
if n == 0:
return 1
else:
return x * exp(x, n - 1)
# retorna x^n, amb n natural
def fastexp(x, n):
if n == 0:
return 1
else:
y = fastexp(x, n//2)
if n%2 == 0:
return y * y
else:
return y * y * x
# retorna x^n mod m
def expmod(x, n, m):
if n == 0:
return 1
else:
y = expmod(x, n//2, m)
if n%2 == 0:
return (y*y) % m
else:
return (((y*y) % m) * x) % m
# -*- coding: UTF-8 -*-
# temps exponencial
def slowfib(n):
if n <= 1:
return n
else:
return slowfib(n - 1) + slowfib(n - 2)
# temps lineal
def fib(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
# retorna X*Y, amb X i Y matrius 2×2
def mult(X, Y):
return [
[ X[0][0]*Y[0][0] + X[0][1]*Y[1][0] , X[0][0]*Y[0][1] + X[0][1]*Y[1][1] ],
[ X[1][0]*Y[0][0] + X[1][1]*Y[1][0] , X[1][0]*Y[0][1] + X[1][1]*Y[1][1] ]
]
# retorna X^n, amb X matriu 2×2
def fastexp(X, n):
if n == 0:
return [ [1, 0],
[0, 1] ]
else:
Y = fastexp(X, n//2)
if n%2 == 0:
return mult(Y, Y)
else:
return mult(mult(Y, Y), X)
# temps logarítmic
def fastfib(n):
M = [ [1, 1] ,
[1, 0] ]
return fastexp(M, n)[0][1]
@jordi-petit
Copy link
Copy Markdown
Author

Proveu quan triga cada versió dels diferents programes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment