Search code examples
c++algorithmpseudocode

Trying to write from pseudocode in c++ (divide_recursive algorithm)


i'm having issues finding this bug on my code, i think it's in the use of array as return data type in the algorithm. I used arrays because c++ doesn't return 2 variables like it's on the pseudocode. The algorithm takes in input 2 integers x and y, and in out gives 2 integers q,r (i use an array a[] of 2 elements) with the quotient and reminders.

pseudocode:

divide(x,y)
    if x = 0: return (q,r) <-- (0,0)
    (q,r) <-- divide(x/2,y)
    q = 2*q, r= 2*r
    if x is odd: r= r+1
    if r>=y: r=r-y, q = q+1
    return(q,r)

c++ code:

    int  divisione(int x, int y)
    {
      int a[1];
        if(x == 0)
        {
            a[0] = 0;
            a[1] = 0;
            return *a;
        }
        int b[1];
        *b = divisione(x/2,y);
        a[0] = b[0]*2;
        a[1] = b[1]*2;
        if((x%2) != 0)
            a[1] = a[1]+1;
        if(a[1]>= y)
        {
            a[0]+=1;
            a[1]-=y;
        }
        return *a;
    }

Solution

  • You have two big problems with your code:

    1. Your array a is declared with a size of 1, not 2, so when you access a[1], you're accessing an element that doesn't exist, which is undefined behavior.

    2. You are only returning the first element of your array. That's what *a means.

    Instead of using an array, just define a structure that matches your pseudocode.

    typedef struct {
        int q;
        int r;
    } DivisionResult;
    
    DivisionResult division(int x, int y) {
        DivisionResult result;
        if (x == 0) {
            result.q = result.r = 0;
            return result;
        }
    
        result = division(x/2, y);
        result.q = result.q * 2;
        result.r = result.r * 2;
        if (x % 2 != 0) {
            result.r = result.r + 1;
        }
        if (result.r >= y) {
            result.q = result.q + 1;
            result.r = result.r - y;
        }
        return result;
    }