A binary algorithm:
You need a prime p for Fp and a number a less than p-1 (larger than 0)
The output will be a^-1 mod p
If you need to calculate b/a mod p ( equals ba^-1 mod a) just substitute x1 with b instead of 1 in the pseudo-code below:
1. s=a, t=p
2. x1 = 1, x2 = 0
3. while (s!= 1 && t != 1) do
3.1. While s even do
s=s/2
if (x1 even) x1 = x1/2 else x1 = (x1+p)/2
3.2. While t even do
t = t/2
if (x2 even) x2 = x2/2 else x2 = (x2+p)/2
3.3. if (s>=t) s = s-t, x1 = x1-x2
else t= t-s, x2 = x2-x1
4. if (s==1) return x1 mod p else return x2 mod p
No comments:
Post a Comment