Search code examples
listpointersdivide-and-conquer

Divide and Conquer multiplication problem c++


I have just started c++ and in the algorythm course there is a pseudo-code and ı have tried it to c++ but ı have failed how can ı convert c++ any clue helps me thanks.

+about multiplication arrays ,this array's elements are constant of x to 1 2 .... n with same size. a1 and b1 is default zero.

+ı write same code in python easily but c++ ı don t know how to break type safety rules.

int* Mult2(int arr1[], int arr2[],int a1,int b1, int size)
{
    int* R = new int[ 2* size - 1];
        if ( size == 1 )
    {
        R[0] = arr1[a1] + arr2 [b1];
        return R;
    } 
    R = Mult2(arr1, arr2, a1, b1, size/2);
    R = Mult2(arr1, arr2, a1+ size/2 , b1+ size/2 , size/2) ;

    int* D0E1 = Mult2(arr1, arr2, a1, b1+size/2, size/2);
    int* D1E0 = Mult2(arr1, arr2, a1+size/2 , b1, size/2);
    R += D0E1 + D1E0;
    return R;
}

error: invalid operands of types 'int*' and 'int*' to binary 'operator+' R += D0E1 + D1E0;


Solution

  • ı can t add two pointer. so

    int* Mult2(int arr1[], int arr2[],int a1,int b1, int size)
    {
        int* R = new int[ 2* size - 1];
            if ( size == 1 )
        {
            R[0] = arr1[a1] + arr2 [b1];
            return R;
        } 
        R = Mult2(arr1, arr2, a1, b1, size/2);
        R = Mult2(arr1, arr2, a1+ size/2 , b1+ size/2 , size/2) ;
    
        int* D0E1 = Mult2(arr1, arr2, a1, b1+size/2, size/2);
        int* D1E0 = Mult2(arr1, arr2, a1+size/2 , b1, size/2);
        for( int i = 0; i < size ; i++)
        {
            R[i] = D0E1[i] + D1E0[i];
        }
        return R;
    }