-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKaratsuba.java
More file actions
39 lines (28 loc) · 1.18 KB
/
Karatsuba.java
File metadata and controls
39 lines (28 loc) · 1.18 KB
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
35
36
37
38
39
package miscellaneous;
public class Karatsuba {
public static void main(String[] args) {
// Examples:
System.out.println(karatsuba(34, 5930)); // 201620
int x = (int) Math.pow(2, Math.random() * (Integer.SIZE - 1)) - 1;
int y = (int) Math.pow(2, Math.random() * (Integer.SIZE - 1)) - 1;
System.out.println(karatsuba(x, y) == x * y); // true
}
public static int karatsuba(int x, int y) {
if (x < 0 || y < 0) {
throw new IllegalArgumentException("No negative factors allowed");
}
int n = Integer.SIZE - Math.min(Integer.numberOfLeadingZeros(x), Integer.numberOfLeadingZeros(y));
int nHalf = n >> 1;
if (n <= 1) {
return x & y;
}
int xHigh = x >> nHalf; // higher n/2 bits
int xLow = x & (1 << nHalf) - 1; // lower n/2 bits
int yHigh = y >> nHalf; // higher n/2 bits
int yLow = y & (1 << nHalf) - 1; // lower n/2 bits
int p1 = karatsuba(xHigh, yHigh);
int p2 = karatsuba(xLow, yLow);
int p3 = karatsuba(xHigh + xLow, yHigh + yLow);
return (p1 << (nHalf << 1)) + ((p3 - (p1 + p2)) << nHalf) + p2;
}
}