Skip to content

Commit

Permalink
feat(field): add modulo, floor div, and enhance operations
Browse files Browse the repository at this point in the history
Implement modulo and floor division operations, add inverse count,
improve power operation counting, and optimize polynomial operations
  • Loading branch information
ahy231 committed Sep 27, 2024
1 parent acc0563 commit 47b1481
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions src/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@ class Field:
'add': 0,
'sub': 0,
'mul': 0,
'div': 0
'div': 0,
'mod': 0,
'ivs': 0,
}

def __init__(self, value):
self.value = value if isinstance(value, list) else [value]

@classmethod
def _increment_count(cls, operation):
cls.operation_counts[operation] += 1
def _increment_count(cls, operation, cnt=1):
cls.operation_counts[operation] += cnt

@classmethod
def get_operation_count(cls, operation=None):
Expand Down Expand Up @@ -74,8 +76,14 @@ def __truediv__(self, other):
def __rtruediv__(self, other):
return self._operate(other, lambda a, b: b / a, 'div')

def __floordiv__(self, other):
return self._operate(other, lambda a, b: a // b, 'div')

def __rfloordiv__(self, other):
return self._operate(other, lambda a, b: b // a, 'div')

def __pow__(self, exponent):
self._increment_count('mul') # Consider power as a series of multiplications
self._increment_count('mul', exponent - 1) # Consider power as a series of multiplications
if isinstance(exponent, int):
if exponent >= 0:
return Field([pow(a, exponent) for a in self.value])
Expand All @@ -89,6 +97,7 @@ def __pow__(self, exponent):
raise TypeError(f"Unsupported exponent type: {type(exponent)}")

def inverse(self):
self._increment_count('ivs')
return Field([1 / a for a in self.value])

def __str__(self):
Expand All @@ -112,6 +121,16 @@ def zero():
def random_element(cls):
return cls(random.randint(0, 193))

def __neg__(self):
self._increment_count('sub') # Negation is essentially subtraction from zero
return Field([-a for a in self.value])

def __mod__(self, other):
return self._operate(other, lambda a, b: a % b, 'mod')

def __rmod__(self, other):
return self._operate(other, lambda a, b: b % a, 'mod')

def magic(Fp):
def magic_field(value):
return Field(Fp(value))
Expand Down

0 comments on commit 47b1481

Please sign in to comment.