public Integer Swap(Integer other) { int s = sign; this.magnitude.Swap(other.magnitude); this.sign = other.sign; other.sign = s; return this; }
public Integer Clone() { Integer n = new Integer(magnitude.Clone()); n.sign = this.sign; return n; }
public Integer SetValue(Integer newVal) { this.magnitude.SetValue(newVal.magnitude); this.sign = newVal.sign; return this; }
/// <summary> /// Returns the smallest positive remainder of the Euclidian divison of x by y. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public static Integer Remainder(Integer x, Integer y) { if (y.sign == 0) throw new DivideByZeroException(); Natural.Modulus(x.magnitude, y.magnitude); // Return smalles positive remainder x.sign = 1; return x; }
public static Integer Subtract(Integer x, Integer y) { y.sign = -y.sign; Integer.Add(x, y); y.sign = -y.sign; return x; // x - y = x + (-y) }
public static Integer Multiply(Integer x, Integer y) { Natural.Multiply(x.magnitude, y.magnitude); x.sign *= y.sign; return x; }
public static Integer Negate(Integer x) { x.sign *= -1; return x; }
/// <summary> /// Returns the smallest (closest to zero) positive or negative remainder of the Euclidian division of x by y. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public static Integer Modulus(Integer x, Integer y) { if (y.sign == 0) throw new DivideByZeroException(); Integer pos = Integer.Remainder(x, y); Integer neg = pos - y; if (neg.magnitude < pos.magnitude) return x.SetValue(neg); // Set x to neg and return else return pos; // x is already pos }
public static Integer Increment(Integer n) { return Integer.Add(n, 1); }
public static Integer Divide(Integer x, Integer y) { if (y.sign == 0) throw new DivideByZeroException(); Natural.Divide(x.magnitude, y.magnitude); x.sign /= y.sign; return x; }
public static Integer Decrement(Integer n) { return Integer.Subtract(n, 1); }
public static Integer Add(Integer x, Integer y) { if (y.sign == 0) return x; else if (x.sign == 0) { x.sign = y.sign; x.magnitude = y.magnitude.Clone(); return x; // Always update x instead of just returning y } else if (x.sign == y.sign) { x.magnitude += y.magnitude; return x; } else { // 5 + (-2) = 5 - (+2) = +3 // 5 + (-7) = 5 - (+7) = -2 // -5 + 2 = -3 // -5 + 7 = +2 if (x.magnitude > y.magnitude) { Natural.Subtract(x.magnitude, y.magnitude); return x; } else if (x.magnitude < y.magnitude) { x.sign = -x.sign; x.magnitude = y.magnitude - x.magnitude; // Can't use in-place subtract here, would create a reference to y's magnitude return x; } else { x.sign = 0; x.magnitude = Natural.Zero; return x; } } }