 # C++ Programming Code Examples

## C++ > Mathematics Code Examples

### Implement Booth's Multiplication Algorithm for Multiplication of 2 signed Numbers

``` Implement Booth's Multiplication Algorithm for Multiplication of 2 signed Numbers This is a C++ Program to multiply two signed numbers using booth's algorithm. Booth's multiplication algorithm is a multiplication algorithm that multiplies two signed binary numbers in two's complement notation. Booth used desk calculators that were faster at shifting than adding and created the algorithm to increase their speed. Booth's algorithm is of interest in the study of computer architecture. #include<iostream> #include<conio.h> using namespace std; void add(int a[], int x[], int qrn); void complement(int a[], int n) { int j; int x = { NULL }; x = 1; for (j = 0; j < n; j++) { a[j] = (a[j] + 1) % 2; } add(a, x, n); } void add(int ac[], int x[], int qrn) { int j, c = 0; for (j = 0; j < qrn; j++) { ac[j] = ac[j] + x[j] + c; if (ac[j] > 1) { ac[j] = ac[j] % 2; c = 1; } else c = 0; } } void ashr(int ac[], int qr[], int &qn, int qrn) { int temp, j; temp = ac; qn = qr; cout << "\t\tashr\t\t"; for (j = 0; j < qrn - 1; j++) { ac[j] = ac[j + 1]; qr[j] = qr[j + 1]; } qr[qrn - 1] = temp; } void display(int ac[], int qr[], int qrn) { int j; for (j = qrn - 1; j >= 0; j--) cout << ac[j]; cout << " "; for (j = qrn - 1; j >= 0; j--) cout << qr[j]; } int main(int argc, char **argv) { int mt, br, qr, sc, ac = { 0 }; int brn, qrn, j, qn, temp; cout << "\n--Enter the multiplicand and multipier in signed 2's complement form if negative--"; cout << "\n Number of multiplicand bit="; cin >> brn; cout << "\nmultiplicand="; for (j = brn - 1; j >= 0; j--) cin >> br[j]; //multiplicand for (j = brn - 1; j >= 0; j--) mt[j] = br[j]; // copy multipier to temp array mt[] complement(mt, brn); cout << "\nNo. of multiplier bit="; cin >> qrn; sc = qrn; //sequence counter cout << "Multiplier="; for (j = qrn - 1; j >= 0; j--) cin >> qr[j]; //multiplier qn = 0; temp = 0; cout << "qn\tq[n+1]\t\tBR\t\tAC\tQR\t\tsc\n"; cout << "\t\t\tinitial\t\t"; display(ac, qr, qrn); cout << "\t\t" << sc << "\n"; while (sc != 0) { cout << qr << "\t" << qn; if ((qn + qr) == 1) { if (temp == 0) { add(ac, mt, qrn); cout << "\t\tsubtracting BR\t"; for (j = qrn - 1; j >= 0; j--) cout << ac[j]; temp = 1; } else if (temp == 1) { add(ac, br, qrn); cout << "\t\tadding BR\t"; for (j = qrn - 1; j >= 0; j--) cout << ac[j]; temp = 0; } cout << "\n\t"; ashr(ac, qr, qn, qrn); } else if (qn - qr == 0) ashr(ac, qr, qn, qrn); display(ac, qr, qrn); cout << "\t"; sc--; cout << "\t" << sc << "\n"; } cout << "Result="; display(ac, qr, qrn); } ``` 