Skip to content

create Karatsuba.java#127

Open
JakeLOLHQ wants to merge 1 commit intoAkatsuki-Coding-Club:mainfrom
JakeLOLHQ:main
Open

create Karatsuba.java#127
JakeLOLHQ wants to merge 1 commit intoAkatsuki-Coding-Club:mainfrom
JakeLOLHQ:main

Conversation

@JakeLOLHQ
Copy link

No description provided.

Comment on lines +14 to +31
public static BigInteger karatsubaMultiply(BigInteger x, BigInteger y) {
int n = Math.max(x.bitLength(), y.bitLength());
if (n <= 3) {
return x.multiply(y);
}
int m = (n + 1) / 2;
// Split x and y into high and low parts
BigInteger xHigh = x.shiftRight(m);
BigInteger xLow = x.subtract(xHigh.shiftLeft(m));
BigInteger yHigh = y.shiftRight(m);
BigInteger yLow = y.subtract(yHigh.shiftLeft(m));
// Recursively compute sub-products
BigInteger a = karatsubaMultiply(xHigh, yHigh);
BigInteger b = karatsubaMultiply(xLow, yLow);
BigInteger c = karatsubaMultiply(xHigh.add(xLow), yHigh.add(yLow)).subtract(a).subtract(b);
// Combine sub-products to get the final result
return a.shiftLeft(2 * m).add(c.shiftLeft(m)).add(b);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wow impressive. i just multiple two integer, but you implemented Karatsuba algorythm literally. i learned a lot by your code. thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants