Skip to content

Instantly share code, notes, and snippets.

@bnlucas
Last active June 3, 2023 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bnlucas/5857525 to your computer and use it in GitHub Desktop.
Save bnlucas/5857525 to your computer and use it in GitHub Desktop.
Solovay-Strassen primality testing with Python.
def solovay_strassen(n, k=10):
if n == 2:
return True
if not n & 1:
return False
def legendre(a, p):
if p < 2:
raise ValueError('p must not be < 2')
if (a == 0) or (a == 1):
return a
if a % 2 == 0:
r = legendre(a / 2, p)
if p * p - 1 & 8 != 0:
r *= -1
else:
r = legendre(p % a, a)
if (a - 1) * (p - 1) & 4 != 0:
r *= -1
return r
for i in xrange(k):
a = randrange(2, n - 1)
x = legendre(a, n)
y = pow(a, (n - 1) / 2, n)
if (x == 0) or (y != x % n):
return False
return True
# benchmark of 10000 iterations of solovay_strassen(100**10-1); Which is not prime.
#10000 calls, 2440 per second.
#571496 function calls (74873 primitive calls) in 4.100 seconds
@barotdhrumil21
Copy link

can you please explain line 14,18 and 26

@kisrefod
Copy link

Check on num 10493450440980479677. It is Prime, but test says that it is composite

@glowbigger
Copy link

Check on num 10493450440980479677. It is Prime, but test says that it is composite

For large numbers, use the decimal library:

def solovay_strassen(n, k=10): from decimal import Decimal n, k = Decimal(n), Decimal(k)

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