mramine364

Karatsuba Multiplication

May 28th, 2016
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. import java.math.BigInteger;
  2.  
  3. public class Karatsuba {
  4.    
  5.     public static void main(String[] args) {        
  6.         BigInteger a = rand(100000), b = rand(100000);
  7.         long t = System.currentTimeMillis();
  8.         a.multiply(b);
  9.         System.out.println("Naive Multiplication (ms)"+(System.currentTimeMillis() - t));
  10.         t = System.currentTimeMillis();
  11.         karatsuba(a, b);
  12.         System.out.println("Karatsuba Multiplication (ms)"+(System.currentTimeMillis() - t));
  13.     }
  14.  
  15.     static BigInteger karatsuba(BigInteger x, BigInteger y){
  16.         BigInteger m,a,b,c,xl,xh,yl,yh;
  17.         m = sqrt(x); m = nextPowerOf2(m);
  18.         xl = x.mod(m); xh = x.divide(m);
  19.         yl = y.mod(m); yh = y.divide(m);
  20.         c = xl.multiply(yl);
  21.         b = xl.add(xh).multiply(yl.add(yh));
  22.         a = xh.multiply(yh);
  23.         return a.multiply(m.pow(2)).add(b.subtract(a).subtract(c).multiply(m)).add(c);
  24.     }
  25.  
  26.     static BigInteger sqrt(BigInteger x) {
  27.         BigInteger div = BigInteger.ZERO.setBit(x.bitLength()/2);
  28.         BigInteger div2 = div;
  29.         for(;;) {
  30.             BigInteger y = div.add(x.divide(div)).shiftRight(1);
  31.             if (y.equals(div) || y.equals(div2))
  32.                 return y;
  33.             div2 = div;
  34.             div = y;
  35.         }
  36.     }
  37.  
  38.     static BigInteger rand(int n){
  39.         String nb = "";
  40.         while( n>0 ){
  41.             nb += (int) (Math.random()*10);
  42.             n--;
  43.         }
  44.         return new BigInteger(nb);
  45.     }
  46.  
  47.     static BigInteger nextPowerOf2( BigInteger n)
  48.     {
  49.         return BigInteger.valueOf(2).pow(n.bitLength());
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment