2

I've got a simple script that I've written to find greatest common divisors (GCDs) and least common multiples (LCMs) using a recursive method- Euclid's algorithm.

Unfortunately if it needs to do this in more than one step the relevant variable to be returned from the function becomes undefined. I've tried following it in a debugger with breakpoints, which seems to follow the recursion adequately and go back to the original function appropriately, but it then mysteriously vanishes at the end of the function even though it's meant to be returned?

Not sure why this is happening or what I can do to fix it. My code is below:

function GCD(a, b) {
    if (a % b == 0) {
        return b;
    }
    else {
        GCD(b, (a % b));
    }
}

function LCM (a, b) {
    return (a*b)/GCD(a, b);
}

function makeDM (a, b) {
    return (GCD(a, b) + " " + LCM(a, b));
}

So if you use a & b such as 60, 20 it will give the correct answers of 20 and 60. However if you use numbers such as 20, 60 or 126, 35 it fails miserably.

6
  • I pasted you code to try in ideone.com, and it gave me the warning on line 2: Use '===' to compare with 0. Commented Mar 31, 2013 at 7:25
  • 4
    One of the paths in GCD doesn't have a return in it. That's fishy. Commented Mar 31, 2013 at 7:28
  • Is this what you're trying to do -> FIDDLE ?? Commented Mar 31, 2013 at 7:29
  • 1
    you are missing a return in the last statement of GCD Commented Mar 31, 2013 at 7:33
  • Thanks guys! Fixed now :). I knew I was missing something fundamental about this. Time to do more reading I guess :D Commented Mar 31, 2013 at 8:11

1 Answer 1

7

You are not returning the value from the recursive part of the function, so the value returned from the function will be undefined. Add a return:

function GCD(a, b) {
    if (a % b == 0) {
        return b;
    }
    else {
        return GCD(b, (a % b));
    }
}

You can also write this with a single return:

function GCD(a, b) {
    return a % b == 0 ? b : GCD(b, (a % b));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thanks so much, I knew I had to have been missing something utterly fundamental hehe :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.