Skip to content

Instantly share code, notes, and snippets.

@primus-lab
Last active December 31, 2019 07:50
Show Gist options
  • Save primus-lab/ea973c8fb19ee63ec49e5560620f64f1 to your computer and use it in GitHub Desktop.
Save primus-lab/ea973c8fb19ee63ec49e5560620f64f1 to your computer and use it in GitHub Desktop.
Probabilistic primality test
# Author: Pedja
import random
print(" ***** CARDANO *****\n\n\n")
while True:
n=int(input("Enter a number : "))
k=int(input("Enter an accuracy parameter : "))
def isprime(n,b,a,m):
F=[[2*a % m,b % m],[1 % m,0 % m]]
expBySquaring(F,n-1,b,a,m)
multiply2(F,a,m)
return F[0][0]==a
def multiply(F,M,m):
x=F[0][0]*M[0][0]+F[0][1]*M[1][0]
y=F[0][0]*M[0][1]+F[0][1]*M[1][1]
z=F[1][0]*M[0][0]+F[1][1]*M[1][0]
w=F[1][0]*M[0][1]+F[1][1]*M[1][1]
F[0][0]=x % m
F[0][1]=y % m
F[1][0]=z % m
F[1][1]=w % m
def multiply2(F,a,m):
x=(F[0][0]*a)+(F[0][1]*1)
y=(F[1][0]*a)+(F[1][1]*1)
F[0][0]=x % m
F[0][1]=y % m
def expBySquaring(F,n,b,a,m):
if n==0 or n==1:
return
M=[[2*a % m,b % m],[1 % m,0 % m]]
expBySquaring(F,n>>1,b,a,m)
multiply(F,F,m)
if (n % 2==1):
multiply(F,M,m)
m=n
if k < 1:
print("Accuracy parameter must be greater than zero")
elif n < 2:
print("Number must be greater than one")
elif n==2 or n==3:
print("probably prime")
elif n==4:
print("composite")
else:
j=0
for i in range(1,k+1):
b=random.randint(-100,100)
a=random.randint(2,n-2)
if(not(isprime(n,b,a,m))):
print("composite")
j+=1
break
if j==0:
print("probably prime")
try_again = ""
# Loop until users opts to go again or quit
while not(try_again == "1") and not(try_again == "0"):
try_again = input("Press 1 to try again, 0 to exit. ")
if try_again in ["1", "0"]:
continue # a valid entry found
else:
print("Invalid input- Press 1 to try again, 0 to exit.")
# at this point, try_again must be "0" or "1"
if try_again == "0":
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment