Question

In: Computer Science

1. Implement the faster algorithm for integer multiplication in C++ as a function, called “multiply”, that...

1. Implement the faster algorithm for integer multiplication in C++ as a function, called “multiply”, that takes 2 unsigned integers and returns their multiplication as an unsigned integer.

2. Test your code in main.

Hints: Represent integers as strings.

Write a utility function that pads integers with zeros, this will be useful If the 2 integers differ in length In calculating ??10^? and (??+??) 10^(?/2)

Solutions

Expert Solution

Karatsuba algorithm is the faster algorithm for integer multiplication. We recursively divide our numbers into two halves until they are small enough to be multiplied using the naive multiplication method.

Numbers X and Y are split into Xl,Xr,Yl,Yr where Xl contains the first half (leftmost n/2) bits of X and Xr contains the second half (rightmost n/2) bits of X. Similarly Yl contains the first half (leftmost n/2) bits of Y and Yr contains the second half (rightmost n/2) bits of Y.

X =  Xl*2n/2 + Xr
Y =  Yl*2n/2 + Yr

So the product XY becomes

XY = (Xl*2n/2 + Xr)(Yl*2n/2 + Yr) = 2n XlYl + 2n/2(XlYr + XrYl) + XrYr

Since big integer arithmetic is not supported by C++, we represent our numbers as string.

C++ code:

#include <iostream>
#include <string>

//Macro to calculate the bigger value
#define max(a,b) ((a) > (b) ? (a) : (b))

using namespace std;

string add(string lhs, string rhs) 
{
    int length = max(lhs.size(), rhs.size());
    int carry = 0;
    int sum_col;  // sum of two digits in the same column
    string result;

    //padding shorter integer with 0's
    while (lhs.size() < length) 
      lhs.insert(0,"0");
            
    while (rhs.size() < length) 
      rhs.insert(0,"0");

    // build result string from right to left
    for (int i = length-1; i >= 0; i--) {
      sum_col = (lhs[i]-'0') + (rhs[i]-'0') + carry;
      carry = sum_col/10;
      result.insert(0,to_string(sum_col % 10));
    }
    
    if (carry)
      result.insert(0,to_string(carry));
    
    //extra 0's are removed
    return result.erase(0, min(result.find_first_not_of('0'), result.size()-1));
}

string subtract(string lhs, string rhs) {
    int length = max(lhs.size(), rhs.size());
    int diff;
    string result;
        
        //padding with 0's
    while (lhs.size() < length) 
      lhs.insert(0,"0");
       
    while (rhs.size() < length) 
      rhs.insert(0,"0");

    for (int i = length-1; i >= 0; i--) {
        diff = (lhs[i]-'0') - (rhs[i]-'0');
        if (diff >= 0)
            result.insert(0, to_string(diff));
        else {

            int j = i - 1;
            while (j >= 0) {
                lhs[j] = ((lhs[j]-'0') - 1) % 10 + '0';
                if (lhs[j] != '9') 
                    break;
                else 
                    j--;
            }
            result.insert(0, to_string(diff+10));
        }
      
    }
        //removing leading 0's
    return result.erase(0, min(result.find_first_not_of('0'), result.size()-1));
}

string multiply(string lhs, string rhs) {
    int length = max(lhs.size(), rhs.size());
    
    while (lhs.size() < length) 
      lhs.insert(0,"0");

    while (rhs.size() < length) 
      rhs.insert(0,"0");

    if (length == 1)
        return to_string((lhs[0]-'0')*(rhs[0]-'0'));

    string lhs0 = lhs.substr(0,length/2);
    string lhs1 = lhs.substr(length/2,length-length/2);
    string rhs0 = rhs.substr(0,length/2);
    string rhs1 = rhs.substr(length/2,length-length/2);
    
    string p0 = multiply(lhs0,rhs0);
    string p1 = multiply(lhs1,rhs1);
    string p2 = multiply(add(lhs0,lhs1),add(rhs0,rhs1));
    string p3 = subtract(p2,add(p0,p1));

    for (int i = 0; i < 2*(length-length/2); i++)
        p0.append("0");
    for (int i = 0; i < length-length/2; i++)
        p3.append("0");
        
    string result = add(add(p0,p1),p3);

    return result.erase(0, min(result.find_first_not_of('0'), result.size()-1));
}

int main() {
    string s1, s2;
    s1="897999802";
    s2="2289311938";
    cout << multiply(s1,s2) << endl;
    return 0;
}

Output for your reference:


Related Solutions

Problem: Write a C/C++ program to implement a function that returns 1 when an integer x...
Problem: Write a C/C++ program to implement a function that returns 1 when an integer x contains an odd number of 1s (in its binary representation) and 0 otherwise. You can consider x as a four byte integer, i.e. w = 32 bits. Constraint: Your solution can use at most 12 arithmetic, bitwise, and logical operations.
Read about the Sieve of Sundaram. Implement the algorithm using function composition. Given an integer n,...
Read about the Sieve of Sundaram. Implement the algorithm using function composition. Given an integer n, your function should generate all the odd prime numbers up to 2n+2. sieveSundaram :: Integer -> [Integer] sieveSundaram = ... To give you some help, below is a function to compute the Cartesian product of two lists. This is similar to zip, but it produces all possible pairs instead of matching up the list elements. For example, cartProd [1,2] ['a','b'] == [(1,'a'), (1,'b'), (2,'a'),...
Develop a recursive algorithm that multiply two integer numbers x and y, where x is an...
Develop a recursive algorithm that multiply two integer numbers x and y, where x is an m-bit number and y is an n-bit number (10 points), and analyze the time complexity of this algorithm (10 points).
In this task you will implement a C++ function with arguments: a sorted integer array, size...
In this task you will implement a C++ function with arguments: a sorted integer array, size of the array, and a target integer value. Find all combinations of two elements in the sorted array which sum up to the target value. When found, add the combinations into an array, and print it. Where there is greater than one combination, you may use the number 200 as a separator for the combinations in the output array. Do not use more than...
In this task you will implement a C++ function with arguments: a sorted integer array, size...
In this task you will implement a C++ function with arguments: a sorted integer array, size of the array, and a target integer value. Find all combinations of two elements in the sorted array which sum up to the target value. When found, add the combinations into an array, and print it. Where there is greater than one combination, you may use the number 200 as a separator for the combinations in the output array. Do not use more than...
Write a C function called weighted_digit_sum that takes a single integer as input, and returns a...
Write a C function called weighted_digit_sum that takes a single integer as input, and returns a weighted sum of that numbers digits. The last digit of the number (the ones digit) has a weight of 1, so should be added to the sum "as is". The second from last digit (the tens digit) has a weight of 2, and so should be multiplied by 2 then added to the sum. The third from last digit should be multiplied by 1...
Using C: Implement four versions of a function funSum that takes a positive integer n as...
Using C: Implement four versions of a function funSum that takes a positive integer n as input and returns the sum of all integers up to and including n that are divisible by 6 or 7: using a for loop in funSum1, using a while loop in funSum2, using a do-while loop in funSum3, and using recursion in funSum4. Your output for the included test code should be: funSum1(20) = 57 funSum2(20) = 57 funSum3(20) = 57 funSum4(20) = 57
Need to write a code using c# Strassen’s Algorithm for matrix multiplication.
Need to write a code using c# Strassen’s Algorithm for matrix multiplication.
write a C++ function called inc whose parameter is an integer reference type and that increases...
write a C++ function called inc whose parameter is an integer reference type and that increases the parameter by one when it is called.
Implement function matmul() that embodies multiplication of n*n matrix in c language?(code) Can you let me...
Implement function matmul() that embodies multiplication of n*n matrix in c language?(code) Can you let me know?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT