Advertisement
LaCaraDeLaVerga

Karatsuba

Aug 11th, 2016
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. package complejidad;
  2.  
  3. import java.math.BigInteger ;
  4. import java.util.Random;
  5.  
  6.  
  7.  
  8. public class Karatsuba {
  9.  
  10.    
  11.     public static BigInteger multiplicar (BigInteger x, BigInteger y){
  12.  
  13.         int m = Math.max(x.bitLength(), y.bitLength())/2 ;
  14.        
  15.         if(m<=10){
  16.             return x.multiply(y);  
  17.         }
  18.         BigInteger x1 = x.shiftRight(m);// googlear shift left y right ;
  19.         BigInteger y1= y.shiftRight(m);
  20.        
  21.  
  22.         BigInteger x2 = x.subtract( x1.shiftLeft(m));      
  23.         BigInteger y2 = y.subtract( y1.shiftLeft(m));      
  24.        
  25.        
  26.         BigInteger A = multiplicar(x1,y1);
  27.         BigInteger B = multiplicar(x2,y2);
  28.         BigInteger C = multiplicar(x1.add(x2),y1.add(y2));
  29.        
  30.         BigInteger K = C.subtract(A.add(B));
  31.        
  32.    
  33.         return A.shiftLeft(2*m).add(K.shiftLeft(m)).add(B);
  34.        
  35.     }
  36.    
  37.     public static void main(String[] args) {
  38. //      Random random = new Random(0);
  39. //      int digitos = 1800;
  40. //      BigInteger x= new BigInteger(digitos,random);
  41. //      BigInteger y= new BigInteger(digitos,random);
  42. //     
  43. //      System.out.println("x= "+x);
  44. //      System.out.println("y= "+y);
  45. //      BigInteger suma = x.add(y);
  46. //
  47. //     
  48. //      System.out.println(suma);
  49. //     
  50. //      long inicio = System.currentTimeMillis();
  51. //      BigInteger zk = multiplicar(x,y);
  52. //      BigInteger zp = x.multiply(y);
  53. //     
  54. //      System.out.println("asd="+zk);
  55. //      System.out.println("asd="+zp);
  56. //     
  57. //     
  58. //      long fin = System.currentTimeMillis();
  59. //      double tiempo = (double) (fin-inicio)/1000;
  60. //      System.out.println(tiempo + " seg");
  61. //     
  62. //     
  63.         Random random =new Random (0);
  64.         BigInteger x= new BigInteger(1800,random);
  65.         BigInteger y= new BigInteger(1800,random);
  66.    
  67.     int cantidad =100000;
  68.     long inicio =System.currentTimeMillis();
  69.     long fin = System.currentTimeMillis();
  70.     double tiempo = (fin-inicio) / (1000.0* cantidad);
  71.     System.out.println( tiempo + "sg");
  72.    
  73.     }
  74.    
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement