from number_theory import gcd class BigFraction: """This is a class for performing extended-precision rational arithmetic. It includes a full suite of operators for arithmetic and it produces a sortable objects, ordered by their numerical values. All BigFractions are stored in a canonical form: they are fully reduced and any negative is stored in the numerator. This class has three static constants ZERO, the BigFraction representing 0 ONE, the BigFraction representing 1 HALF, the BigFraction representing 1/2 """ ZERO = None ONE = None HALF = None def __init__(self, num, denom): """This accepts two integer argments, a numerator and a denominator. A zero denominator will trigger a ValueError.""" if denom == 0: raise ValueError if denom < 0: num = -num denom = -denom d = gcd(num, denom) self.num = num//d self.denom = denom//d def __str__(self): """This returns a string represenation for this BigFraction of the form numerator/denominator.""" return f"{self.num}/{self.denom}" def __repr__(self): """This returns a string representation of the form BigFraction(numerator, denominator) suitable for the Python REPL""" return f"BigFraction({self.num}, {self.denom})" def __add__(self, other): """This defines + and returns the sum of two BigFractions.""" top = self.num*other.denom + self.denom*other.num bottom = self.denom*other.denom return BigFraction(top, bottom) def __sub__(self, other): """This defines - and returns the difference of two BigFractions.""" top = self.num*other.denom - self.denom*other.num bottom = self.denom*other.denom return BigFraction(top, bottom) def __mul__(self, other): """This defines * and returns the product of two BigFractions.""" top = self.num*other.num bottom = self.denom*other.denom return BigFraction(top, bottom) def __truediv__(self, other): """This defines / and returns the quotient of two BigFractions.""" top = self.num*other.denom bottom = self.denom*other.num return BigFraction(top, bottom) def __pow__(self, n): """This defines ** and returns this BigFraction raised to the nth power. This works for both positive and negative integers.""" if n == 0: return BigFraction(1,1) if n > 0: return BigFraction(self.num**n, self.denom**n) n = -n return BigFraction(self.denom**n, self.num**n) @staticmethod def init_static(): """initializes the static constants ZERO, HALF, and ONE.""" BigFraction.ZERO = BigFraction(0,1) """The Big Fraction 0/1""" BigFraction.ONE = BigFraction(1,1) """The Big Fraction 1/1""" BigFraction.HALF = BigFraction(1,2) """The Big Fraction 1/2""" BigFraction.init_static()