Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
1
Problem Definition
• Given two decimal numbers consisting of “N”
digits, design an algorithm to multiply them
efficiently
3
Representing Long Integers
• You can simply use an array
– Each slot of the array keeps one digit of the number
– A[0] stores the least significant digit
– A[N-1] stores the most-significant digit
• Example:
– char A[] = {4, 1, 5, 3, 2}; // 23514
– char B[] = {9, 5, 2, 1}; // 1259
4
Operations on Long Integers
• Addition and subtraction is easy
– Simply add/subtract digit by digit – O(N)
5
D&Q Long Integer Multiplication
n
n/2 n/2
w x A
y z B
wz xz
wy xy
wy wz + xz xz P=A*B
6
D&Q Long Integer Multiplication
n
n/2 n/2
w x A
y z B
• Let m = n/2
• A = w*10m + x
• B = y*10m + z
1 if n =1 (Base case)
T(n) = T(n) = (n2)
4*T(n/2) + n if n>1
Faster Long Integer Multiplication
n
n/2 n/2
w x A
y z B
• C = Mult(w, y)
• D = Mult(x, z)
• E = Mult((w+x), (y+z)) - C - D;
• Product = C*102m + E*10m + D;
Mult(w, y, C, N/2);
Mult(x, z, D, N/2);
Mult(w+x, y+z, E, N/2);
E -= C – D;
P = C*102m + E*10m + D;
} //end-Mult
1 if n =1 (Base case)
T(n) = T(n) = (n1.585)
3*T(n/2) + n if n>1
Summary of Long Int Multiplication
• Brute-force iterative algorithm = (n2)
• Divide & Conquer algorithm = (n1.585)
11