Exemplo n.º 1
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;
  }