"""A Module that can do Modular arithmetic. Some things to try: seq = [Modular(i) for i in range(7)] a_seq = [Modular(2)] while a_seq[-1]!=1: a_seq.append(a_seq[-1]*a_seq[0]) """ from __future__ import division, print_function class Modular(object): """A class that enables simple modular arithmetic. Parameters ---------- x: int or float The value, or Modular object from which a value is copied. base: int (optional) The base for modular arithmetic. """ def __init__(self, x, base=13): if type(x).__name__ == 'Modular': self.value = x.value self.base = x.base else: self.value = x % base self.base = base def __repr__(self): return str(self.value) def __add__(self, other): other = Modular(other) if self.base != other.base: print("Only modular numbers with the same base can be added.") raise ArithmeticError retval = (self.value + other.value) % self.base return Modular(retval) def __sub__(self, other): other = Modular(other) if self.base != other.base: print("Only modular numbers with the same base can be subtracted.") raise ArithmeticError retval = (self.value - other.value) % self.base return Modular(retval) def __mul__(self, other): other = Modular(other) if self.base != other.base: print("Only modular numbers with the same base can be multiplied.") raise ArithmeticError retval = (self.value * other.value) % self.base return Modular(retval) def __eq__(self, other): other = Modular(other) return self.value==other.value def __ne__(self, other): other = Modular(other) return self.value!=other.value def __radd__(self, other): return self.__add__(other) def __rsub__(self, other): return -self.__sub__(other) def __neg__(self): return self.base - self.value