/*---- Assumes both HugeIntegers are positive and this > that -----------------*/ public HugeInteger subtract(HugeInteger that) { if (this.compareTo(that) < 0) return that.subtract(this); HugeInteger result = new HugeInteger(this.size()); int borrow = 0; int difference; int position = 0; for (; position < that.size(); position++) { difference = this.digitAt(position) - that.digitAt(position) - borrow; if (difference < 0) { difference += 10; borrow = 1; } else { borrow = 0; } result.addDigit(difference); DIGIT_OPERATIONS++; } for (; position < this.size(); position++) { difference = this.digitAt(position) - borrow; if (difference < 0) { difference += 10; borrow = 1; } else { borrow = 0; } result.addDigit(difference); DIGIT_OPERATIONS++; } result.removeLeadingZeroes(); return result; }
/*---- returns the sum of this and the provided HugeInteger -------------------*/ public HugeInteger add(HugeInteger that) { this.removeLeadingZeroes(); that.removeLeadingZeroes(); HugeInteger result = new HugeInteger(max(this.size(), that.size())); int carry = 0; int position = 0; int sum; while (position < min(this.size(), that.size())) { sum = this.digitAt(position) + that.digitAt(position) + carry; if (sum >= 10) { sum -= 10; carry = 1; } else { carry = 0; } result.addDigit(sum); position++; DIGIT_OPERATIONS++; } if (this.size() > that.size()) { while (position < this.size()) { result.addDigit(this.digitAt(position) + carry); carry = 0; position++; DIGIT_OPERATIONS++; } } else if (that.size() > this.size()) { while (position < that.size()) { result.addDigit(that.digitAt(position) + carry); carry = 0; position++; DIGIT_OPERATIONS++; } } if (carry == 1) { result.addDigit(1); } return result; }
/*---- multiplies this and the specified HugeInteger using "school" algorithm -*/ public HugeInteger multiply(HugeInteger that) { // create zero-filled HugeInteger int resultSize = this.size() + that.size(); ArrayList<Integer> list = new ArrayList<Integer>(Collections.nCopies(resultSize, 0)); HugeInteger result = new HugeInteger(list); int carry = 0; int m; for (int i = 0; i < that.size(); i++) { for (int j = 0; j < this.size(); j++) { m = this.digitAt(j) * that.digitAt(i); m = m + carry + result.digitAt(i + j); result.setDigit(i + j, m % 10); carry = m / 10; DIGIT_OPERATIONS += 3; // three digit operations: two add, one multiply } if (carry > 0) { result.setDigit(i + this.size(), result.digitAt(i + this.size()) + carry); carry = 0; } } result.removeLeadingZeroes(); return result; }
/*---- compares this HugeInteger to provided HugeInteger for order ------------*/ public int compareTo(HugeInteger that) { if (this == that) return 0; else if (this.size() > that.size()) { return 1; } else if (this.size() < that.size()) { return -1; } else { for (int i = this.size() - 1; i >= 0; i--) { int thisDigit = this.digitAt(i); int thatDigit = that.digitAt(i); DIGIT_OPERATIONS++; if (thisDigit > thatDigit) return 1; else if (thisDigit < thatDigit) return -1; } return 0; } }