Answer the question
In order to leave comments, you need to log in
How to implement multiplication of large numbers in Java?
I'm going through an online course, the second day I'm struggling with the task. Unable to pass the test, gives an error: “Failed test #7. Time limit exceeded” . You have to complete the task within 5 seconds. Tell me how to speed up, or point out errors, if any
. Task:
Implement the multiplication of two numbers by the Karatsuba algorithm, the length of which does not exceed 100000. Print their product.
import java.math.*;
import java.io.*;
class prog{
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BigInteger A = new BigInteger(br.readLine().trim());
BigInteger B = new BigInteger(br.readLine().trim());
System.out.printf((kara(A, B)).toString());
}
public static BigInteger kara(BigInteger x, BigInteger y) {
int N = Math.max(x.bitLength(), y.bitLength());
if (N <= 2000) return x.multiply(y);
N = (N / 2) + (N % 2);
BigInteger b = x.shiftRight(N);
BigInteger a = x.subtract(b.shiftLeft(N));
BigInteger d = y.shiftRight(N);
BigInteger c = y.subtract(d.shiftLeft(N));
BigInteger ac = kara(a, c);
BigInteger bd = kara(b, d);
BigInteger abcd = kara(a.add(b), c.add(d));
return ac.add(abcd.subtract(ac).subtract(bd).shiftLeft(N)).add(bd.shiftLeft(2*N));
}
}
Answer the question
In order to leave comments, you need to log in
Before you need to exit the recursion, treat these large numbers as if they were strings. As soon as you need a numeric value - only then convert.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question