首页 > 解决方案 > 一个支持加法和否定的模整数的python类?

问题描述

我正在尝试为python中的定义添加和否定提供代码。我拥有的最相似的东西是乘法,我在下面复制了它。关于应该改变什么以解释模整数的加法和否定的任何想法?我知道减法只是在这个问题中添加否定。任何帮助将非常感激!!

class Zp:

    p = 2 #class attribute

    def __init__(self, n):
        self.n = n % Zp.p #instance attribute

    def __str__(self):
        #msg = '[' + str(self.n) + ']'
        msg = str(self.n) + ' mod ' + str(Zp.p) + ')'
        return msg

    def __repr__(self):
        return self.__str__()

    # def __add__(self, other):
        # [a], [b] in Zp ([a], [b] are sets of integers)
        # [a]+[b] = [a+b] e.g. a+b mod p
    # def __neg__(self, other):
    # def __sub__ (self, other): # the addition of negation

    def __mul__(self, other): # [a]*[b] = [a*b] e.g. a*b mod p
        if Zp.__instancecheck__(other):
            return Zp(self.n * other.n)
        elif type(other) == int:
            return Zp(self.n * other)
        else:
            raise TypeError('multiplication a Zp with a non-Zp or non-integer')

我尝试添加的内容:

def __add__(self, other): # [a]*[b] = [a*b] e.g. a*b mod p
        if Zp.__instancecheck__(other):
            return Zp(self.n + other.n)
        elif type(other) == int:
            return Zp(self.n + other)

标签: pythonpython-3.x

解决方案


在对数字进行模运算时,通常可以进行正常运算(加法、减法、乘法),然后将答案模数取模。

例如,

3 * 3 模 2 = 9 模 2 = 1 模 2

为了实现您指定的操作,请执行操作,然后取模。查看 Wikipedia 的文章,了解有关如何进行模运算的更多信息:Modular Arithmetic - Wikipedia


推荐阅读