forked from dharmanshu1921/Daa-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKaratsuba.java
More file actions
57 lines (50 loc) · 1.56 KB
/
Karatsuba.java
File metadata and controls
57 lines (50 loc) · 1.56 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.company.assignments;
import java.util.Scanner;
/** Class Karatsuba **/
public class Karatsuba {
public long multiply(long x, long y) {
int size1 = getSize(x);
int size2 = getSize(y);
int N = Math.max(size1, size2);
if (N < 10)
return x * y;
N = (N / 2) + (N % 2);
long m = (long) Math.pow(10, N);
long b = x / m;
long a = x - (b * m);
long d = y / m;
long c = y - (d * N);
/** compute sub expressions **/
long z0 = multiply(a, c);
long z1 = multiply(a + b, c + d);
long z2 = multiply(b, d);
return z0 + ((z1 - z0 - z2) * m) + (z2 * (long) (Math.pow(10, 2 * N)));
}
/**
* Function to calculate length or number of digits in a number
**/
public int getSize(long num) {
int ctr = 0;
while (num != 0) {
ctr++;
num /= 10;
}
return ctr;
}
/**
* Main function
**/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Karatsuba Multiplication Algorithm Test\n");
/** Make an object of Karatsuba class **/
Karatsuba kts = new Karatsuba();
/** Accept two integers **/
System.out.println("Enter two integer numbers\n");
long n1 = scan.nextLong();
long n2 = scan.nextLong();
/** Call function multiply of class Karatsuba **/
long product = kts.multiply(n1, n2);
System.out.println("\nProduct : " + product);
}
}