This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

I need help with the following code to find greatest common divisor.

Greenhorn
Posts: 18
Hello, I need help with the following code. It does not work with all cases for example if i enter 84 and 48.

Matthew Brown
Bartender
Posts: 4568
9
What formula are you trying to use to get the GCD? The code isn't right, but I don't know if you've got an incorrect implementation of the right algorithm, or a correct implementation of the wrong algorithm. At the moment you're just taking the modulus of one of the values with respect to the other, which isn't correct.

Take the example you've given: 84 and 48. Your code just calculates 84 % 48, which is 36, which isn't a common divisor of either of them. The easiest approach I know is probably the Euclidean algorithm, which uses modular arithmetic, but needs multiple calculations (so either a loop or a recursive function). The recursive calculation goes something like:

Rob Spoor
Sheriff
Posts: 20709
68
There's a flaw in there somewhere; the GCD is not 4 but 12. That's because 48 % 36 is not 8 but 12. The flow then becomes this:

Matthew Brown
Bartender
Posts: 4568
9
Good point. Thanks!

(Typical mathematician - can cope with the difficult stuff and then makes errors with basic arithmetic )