0

another one of these stupid questions. I have a very simpe algorithm here to calculate the greatest commen divider.

My C++ snippet looks like this

int findGcd(int m, int n)
{
    int r = m % n;

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

    else
    {
        m = n;
        n = r;
        findGcd(m, n);
    }
}

int main()
{
    cout << findGcd(13, 3);

    return 0;
}

... And it returns (exactly as expected in this example) 1.

If I implement it in Python though - like the following:

def findGcd(m, n):
"""Calculates the greatest common divider """
    r = m % n

    if r == 0:
        return n

    else:
        m = n
        n = r
        findGcd(m, n)




number = findGcd(13,3)
print(number)

It just returns NONE instead of 1. I already debugged it and n did indeed have the correct value of 1 stored in it but returns None none the less.

I can fix this by adding "return" to my recursive call of the function in the else branch. But why is that?

Andy M.
  • 23
  • 5
  • I cannot reproduce your output in C++ – juanpa.arrivillaga Dec 07 '18 at 05:47
  • 1
    @juanpa.arrivillaga, that's because, in C++, the missing `return` causes undefined behavior. – R Sahu Dec 07 '18 at 05:50
  • I was using an online C++ compiler. Turns out it was s#*t. Sorry for wasting your time on this one. The misunderstanding was just caused by the compilers unexpected behaviour. Thanks for your help though! – Andy M. Dec 07 '18 at 05:54
  • Note, there *are* languages that have return statements that *will* implicitly return, e.g. Scala. You shouldn't assume, though, that because something works in C++ (or in this case, it didn't) or Scala that it will work in Python. – juanpa.arrivillaga Dec 07 '18 at 06:00

1 Answers1

1

In both cases, you need a return in the recursive call.

Without that, in C++, you have undefined behavior. In Python, you get None.

C++

int findGcd(int m, int n)
{
    int r = m % n;

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

    else
    {
        m = n;
        n = r;
        return findGcd(m, n);
    }
}

Python:

def findGcd(m, n):
"""Calculates the greatest common divider """
    r = m % n

    if r == 0:
        return n

    else:
        m = n
        n = r
        return findGcd(m, n)

You catch such problems in C++ by increasing the warning level on your compiler. With g++ -Wall, I get:

socc.cc: In function ‘int findGcd(int, int)’:
socc.cc:16:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^
R Sahu
  • 204,454
  • 14
  • 159
  • 270