[Python] Python class that does integer operations mod n

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to create a Python class that does operations mod n. For example using mod 100:

    11*11==21
    66+39==5
    1+2+3-30==73
    2**10==24


    This is how I am doing it:

    class ModInteger:
    def __init__(self, value, mod):

    self.mod = mod
    self.value = value % mod
    return self

    def __add__(self, other):
    return ModInteger((self.value + other.value) % self.mod, self.mod)
    def __sub__(self, other):
    return ModInteger((self.value - other.value) % self.mod, self.mod)
    def __mul__(self, other):
    return ModInteger((self.value * other.value) % self.mod, self.mod)
    def __pow__(self, other):
    return ModInteger((self.value ** other.value) % self.mod, self.mod)
    #...


    It works, but is there a less tedious way of doing it?

    Continue reading...

Compartilhe esta Página