-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKaratsuba.java
More file actions
33 lines (27 loc) · 772 Bytes
/
Karatsuba.java
File metadata and controls
33 lines (27 loc) · 772 Bytes
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
import java.util.Scanner;
/**
* Karatsuba
*/
public class Karatsuba {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long a=sc.nextLong();
long b=sc.nextLong();
System.out.println(karatsuba(a,b));
}
public static long karatsuba(long x ,long y) {
if(x<10||y<10)
return x*y;
int m=Math.max((""+x).length(),(""+y).length());
long powOf10=(long)Math.pow(10,m/2);
long a=x/powOf10;
long b=x%powOf10;
long c=y/powOf10;
long d=y%powOf10;
long ac=karatsuba(a,c);
long bd=karatsuba(b,d);
long abcd=karatsuba(a+b,c+d);
long res=ac*(long)Math.pow(10,m)+(abcd-ac-bd)*powOf10+bd;
return res;
}
}