human
I am working on the file "Clock Arithmetic.ipynb".
The first task is:
For example, pow(M(79), -2) means find the inverse of M(79) e.g. M(79)**-1, and then raise the result to the 2nd power.
Can you write Python program for it?
assistant
#Here is Python program to find the inverse of M(79) e.

class M:  # for "modulo"
    
    """
    Version 2, with inverting and powering added
    Version 3, not listed, is in groups.py and uses xgcd (next Chapter)
    """
    
    modulus = 10  # class level
    
    def __init__(self, val, modulus=None):
        if modulus:
            self.modulus = M.modulus = modulus # resettable
        else:
            self.modulus = M.modulus
        self.val = val % M.modulus
        
    def __add__(self, other):
        if self.modulus != other.modulus:
            raise ValueError
        return M(self.val + other.val, self.modulus)
    
    def __mul__(self, other):
        if self.modulus != other.modulus:
            raise ValueError
        return M(self.val * other.val, self.modulus)

    def __invert__(self):
        elems = {M(x) for x in totatives(self.modulus)}
        for m in elems:
            if (self * m).val == 1:
                return m
    
    def __pow__(self, exp):  # pow() and ** both trigger this method
        output = self
        if exp < 0:
            exp = abs(exp)  # make exp positive now
            output = ~self  # -1 means take the inverse
        elif exp == 0:
            output = M(1)   # return identity if exp is 0
        elif exp == 1:
            output = self   # return M if exp is 1
        if exp > 1:
            for _ in range(1, exp):  # use __mul__ (already defined)
                output *= self
        
        return output
    
    def __repr__(self):
        return "(" + str(self.val) + " mod " + str(M.modulus)+ ")"

M.modulus = 100
a = M(79)
a_inv = pow(a, -1)
a_inv

M(13) * M(13) * M(13)

M(13)**3       # confirm this is another way of saying it (we're testing)

M(13)**-1      # give me the inverse of M(13) please

M(13) * M(77)  # these must be inverses then