create a function to construct a finite field in python

To create a function to construct a finite field in Python, you can use a class to represent the finite field. Here is an example implementation:

main.py
class FieldElement:
    def __init__(self, num, prime):
        if num >= prime or num < 0:
            error = 'Num {} not in field range 0 to {}'.format(num, prime-1)
            raise ValueError(error)

        self.num = num
        self.prime = prime

    def __repr__(self):
        return 'FieldElement_{}({})'.format(self.prime, self.num)

    def __eq__(self, other):
        if other is None:
            return False
        return self.num == other.num and self.prime == other.prime

    def __ne__(self, other):
        if other is None:
            return False
        return not (self == other)

    def __add__(self, other):
        if self.prime != other.prime:
            raise TypeError('Cannot add two numbers in different Fields')
        num = (self.num + other.num) % self.prime
        return self.__class__(num, self.prime)

    def __sub__(self, other):
        if self.prime != other.prime:
            raise TypeError('Cannot subtract two numbers in different Fields')
        num = (self.num - other.num) % self.prime
        return self.__class__(num, self.prime)

    def __mul__(self, other):
        if self.prime != other.prime:
            raise TypeError('Cannot multiply two numbers in different Fields')
        num = (self.num * other.num) % self.prime
        return self.__class__(num, self.prime)

    def __rmul__(self, coeff):
        num = (self.num * coeff) % self.prime
        return self.__class__(num=num, prime=self.prime)

    def __pow__(self, n):
        n = n % (self.prime - 1)
        num = pow(self.num, n, self.prime)
        return self.__class__(num=num, prime=self.prime)

    def __truediv__(self, other):
        if self.prime != other.prime:
            raise TypeError('Cannot divide two numbers in different Fields')
        num = (self.num * pow(other.num, self.prime - 2, self.prime)) % self.prime
        return self.__class__(num=num, prime=self.prime)

1927 chars
56 lines

This implementation defines a FieldElement class that can be used to represent elements of finite fields. An instance of this class can be created by specifying the field's modulus and the number to be represented by the element. This implementation also support basic arithmetic operations such as addition, subtraction, multiplication, and division.

To use this implementation, you can create an instance of the FieldElement class as follows:

main.py
a = FieldElement(7, 13)
print(a)
33 chars
3 lines

This will output FieldElement_13(7).

related categories

gistlibby LogSnag