#EXTENDED EUCLIDEAN ALGORITHM TO FIND GCD(M,B)
m=int(raw_input("ENTER M OR mod M = : "))
b=int(raw_input("ENTER B = : "))
# A1,A2,A3 <---(1,0,M)
a1=1
a2=0
a3=m
# B1,B2,B3 <---(0,1,B)
b1=0
b2=1
b3=b
while 1 :
# if B3=0 return A3=GCD(M,B) and B has no inverse
if b3==0 :
gcd_MB=a3
invrs_b=0
break
# if B3=1 return B3=GCD(M,B) and B2=B(inverse) mod M
if b3==1 :
gcd_MB=b3
invrs_b=1
break
# Q=A3/B3
q=a3/b3
# (T1,T2,T3) <--- [(A1-QB1),(A2-QB2),(A3-QB3)]
t1=a1-q*b1
t2=a2-q*b2
t3=a3-q*b3
# (A1,A2,A3) <--- (B1,B2,B3)
a1=b1
a2=b2
a3=b3
# (B1,B2,B3) <--- (T1,T2,T3)
b1=t1
b2=t2
b3=t3
if invrs_b==0 :
print "\nGCD(B,M) = : ",gcd_MB,"\n"
print "\n", b,"HAS NO MULTIPLICATIVE INVERSE IN mod",m,"\n"
if invrs_b==1 :
#FIND THE MULTIPLICATIVE INVERSE OF B IN mod M by traditional method......
c=1
while ((b*c)%m)!=1 :
c=c+1
if c>m :
break
#FIND MULTIPLICATIVE INVERSE OF B IN mod M BY value of b2.......
#c=1
#while c%m!=b2 :
# c++
# if (c>m) :
# break
if c<m :
print "\nGCD(B,M) = :",gcd_MB
print "\nMULTIPLICATIVE INVERSE OF",b, " = " ,c, " in mod",m,"\n"
else:
print "\nGCD(B,M) = : ",gcd_MB
print "\n",b," HAS NO INVERSE IN mod",m,"\n"
Compile and run in a single command :
system path> python eea.py
It will compile as well as run the program.
No comments:
Post a Comment