-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfinite_field_arithmetic.py
46 lines (33 loc) · 1.22 KB
/
finite_field_arithmetic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#################################################################################
# Modular arithmetic in the field of p elements
#################################################################################
class field:
def __init__(self, p):
self.p = p
# returns inverse of g modulo p (use Fermat's little theorem)
def inverse(self, g):
return field.fast_powering_algorithm(self, g, self.p-2)
# Fast powering algorithm to compute g^n (mod p)
def fast_powering_algorithm(self, g, n):
bits = format(n, '0b')
cont = len(bits)
L = []
for bit in bits:
cont = cont-1
if bit == '1':
k = g
for i in range(cont):
k = k**2 % self.p
L.append(k)
result = 1
for factor in L:
result = result*factor % self.p
return result
# Return order of element g mod p
def order(self, g):
order, k = 1, g
p = self.p
while k != 1:
k = (k * g) % p
order = order+1
return order