-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnyBaseMultiplication.java
More file actions
64 lines (55 loc) · 1.49 KB
/
AnyBaseMultiplication.java
File metadata and controls
64 lines (55 loc) · 1.49 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
58
59
60
61
62
63
package Data_Structure_And_Algorithm;
import java.util.Scanner;
public class AnyBaseMultiplication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
int b = scanner.nextInt();
System.out.println(product(n1, n2, b));
}
public static int product(int n1, int n2, int b){
int num = 0;
int p = 1;
while (n2 > 0){
int r2 = n2 % 10;
n2 /= 10;
int temp = getProductWithSingleDigit(n1, r2, b);
num = addition(num, temp * p, b);
p *= 10;
}
return num;
}
public static int getProductWithSingleDigit(int n1, int d2, int b){
int num = 0;
int carry = 0;
int p = 1;
while (n1 > 0 || carry > 0){
int r1 = n1 % 10;
n1 /= 10;
int r = r1 * d2 + carry;
carry = r / b;
r %= b;
num += r * p;
p *= 10;
}
return num;
}
public static int addition(int n1, int n2, int b){
int sum = 0;
int carry = 0;
int p = 1;
while (n1 > 0 || n2 > 0 || carry > 0){
int r1 = n1 % 10;
int r2 = n2 % 10;
n1 /= 10;
n2 /= 10;
int r = r1 + r2 + carry;
carry = r / b;
r %= b;
sum += r * p;
p *= 10;
}
return sum;
}
}