Recursive function

Asked

Viewed 672 times

1

Can anyone help me with this recursive function? It’s for her to calculate the maximum common divisor between two numbers but I don’t know what’s wrong with my function.

    int mdc(int m, int n){
        int aux;
        if(n>m || n<0){
            return 0;
        }
        else{
            aux=mdc(n, m % n);
            return aux;
        }

    }

2 answers

1

the stopping condition for the Euclides algorithm (used to find mdc) is when it finds a remainder = 0 and when it occurs it returns the divisor that took this remainder to be 0

if(n == 0 ){
    return m;
}

N after the first call of the function is the rest of a division and M is the divisor that led to the rest

  • It worked!!! Thank you very much.

1

The maximum common divisor (mdc) of the integers x and y is the largest integer that is divisible by x and y. It is defined as follows:

mdc(x, y) = y, if x >= y and x mod y=0

mdc(x, y) = mdc (y, x), if x < y

mdc(x, y) = mdc (y, x mod y), otherwise (if x > y).

int mdc(int x, int y) {
    if (x < y) {
        return mdc(y, x);
    }
    else {
        if (x % y == 0)
            return y;
        else
            return mdc(y, x%y);
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.