-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathKaratsuba algorithm.java
34 lines (32 loc) · 997 Bytes
/
Karatsuba algorithm.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class demo
{
static int Karatsuba(int X,int Y)
{
System.out.println("Karatsuba("+X+","+Y+")");
if(X<10 && Y<10)
{
return X*Y;
}
else
{
int xlength = Integer.toString(X).length();
int ylength = Integer.toString(Y).length();
int n = (xlength>=ylength)? xlength : ylength;
int halfN = n/2;
int a = X /(int)Math.pow(10, halfN);
int b = X %(int)Math.pow(10, halfN);
int c = Y /(int)Math.pow(10, halfN);
int d = Y %(int)Math.pow(10, halfN);
int ac = Karatsuba(a, c);
int bd = Karatsuba(b, d);
int ad_plus_bc = Karatsuba(a+b, c+d) - ac - bd;
return ac*(int)Math.pow(10, 2*halfN) + (ad_plus_bc) * (int)Math.pow(10, halfN) + bd;
}
}
public static void main(String[] args)
{
int X = 1234;
int Y = 5678;
System.out.println(Karatsuba(X, Y));
}
}