Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private static int nDigits(long x) {
- int digits = 0;
- do {
- digits++;
- x /= 10;
- } while (x != 0);
- return digits;
- }
- private static long multiply(long x, long y) {
- // x = a * 10^(N/2) + b;
- // y = c * 10^(N / 2) + d
- int N = nDigits(x);
- if (N == 1)
- return x * y;
- //Divide
- int digits = (int) Math.pow(10, N / 2);
- long a = x / digits;
- long b = x % digits;
- long c = y / digits;
- long d = y % digits;
- // Solve
- long p1 = multiply(a, c);
- long p2 = multiply(b, d);
- long aux = multiply(a + b, c + d);
- long p3 = aux - p1 - p2;
- return (p1 * (long) Math.pow(10, N) + p3 * (long) Math.pow(10, N / 2) + p2);
- }
- public static void main(String[] args) {
- long x = 1234;
- long y = 5678;
- System.out.println(multiply(x, y));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement