예제 #1
0
 /*---- 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;
 }
예제 #2
0
  /*---- using Karatsuba Ofman fast algorithm -----------------------------------*/
  public HugeInteger fastMultiply(HugeInteger that) {
    // this.removeLeadingZeroes();
    // that.removeLeadingZeroes();
    if (this.size() <= 5 || that.size() <= 5) return this.multiply(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 midPoint = (min(this.size(), that.size())) / 2;
    HugeInteger a = this.upperCopy(midPoint);
    HugeInteger b = this.lowerCopy(midPoint);
    HugeInteger c = that.upperCopy(midPoint);
    HugeInteger d = that.lowerCopy(midPoint);
    System.out.println(a + "|" + b + " * " + c + "|" + d);
    HugeInteger low = b.fastMultiply(d);
    System.out.printf("b*d: %42s\n", low.toString());
    HugeInteger high = a.fastMultiply(c);
    System.out.printf("a*c: %42s\n", high.toString());
    HugeInteger mid = a.add(b);
    mid = mid.fastMultiply(c.add(d));
    System.out.printf("a+b: %42s\n", a.add(b).toString());
    System.out.printf("c+d: %42s\n", c.add(d).toString());
    System.out.printf("a+b*c+d: %38s\n", mid);
    mid = mid.subtract(high);
    mid = mid.subtract(low);
    System.out.printf("preshift: %37s\n\n", mid.toString());
    System.out.printf("mid: %42s\n", mid.shift(midPoint).toString());
    System.out.printf("hi : %42s\n", high.shift(2 * midPoint).toString());
    System.out.printf("low: %42s\n", low.toString());
    high = high.shift(2 * midPoint);
    // System.out.println("\n\n"+mid);
    mid = mid.shift(midPoint);
    // System.out.println("\n\n"+mid);
    result = result.add(low);
    result = result.add(mid);
    result = result.add(high);
    result.removeLeadingZeroes();
    System.out.printf("total: %40s\n\n", result.toString());
    return result;
  }