gcd function bug?

gcd function bug?

by Ton Boerkoel -
Number of replies: 4

I noticed that the gcd function doesn't give correct results when one of the values is 0.

For example when we let   a=0; b=6;  and  g=gcd(a,b); 

then  {g}  appeared in the problem as  1.   So apparently gcd(0,6) = 1   (it should be 6 of course).

And  g=gcd(0,0)  returned  {g}  as  1  as well.   

Average of ratings: -
In reply to Ton Boerkoel

Re: gcd function bug?

by Dominique Bauer -
Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Plugin developers

Hello Ton,

I'll correct this as soon as I can. In the meantime, here's a one-line fix, where I have defined gcd(0,0) = 0.

Instead of writing:

g = gcd(a,b);

write:

g = a==0&&b==0?0:(a==0?b:(b==0?a:gcd(a,b)));
In reply to Dominique Bauer

Re: gcd function bug?

by Dominique Bauer -
Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Plugin developers

Oops, the correct formula is:

g = a==0&&b==0?0:(a==0?abs(b):(b==0?abs(a):gcd(a,b)));
In reply to Dominique Bauer

Re: gcd function bug?

by Ton Boerkoel -
Yes, I realized I could do that, but I needed g = gcd(a, gcd(b ,c)) and g = gcd(gcd(a,b ),gcd(c,d)) etc. Building definitions for all of these, accounting for all possible a==0, b==0, c==0 and d==0, is not what I wanted to do. smile


In reply to Ton Boerkoel

Re: gcd function bug?

by Dominique Bauer -
Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Plugin developers

Ton,

You have already reported the bug. Thank you. I will try to correct it as soon as possible.

In the meantime, it wouldn't have taken you much longer to write:

ab = a==0&& b==0?0:(a==0?abs(b):(b==0?abs(a):gcd(a,b)));
bc = b==0&& c==0?0:(b==0?abs(c):(c==0?abs(b):gcd(b,c)));
cd = c==0&& d==0?0:(c==0?abs(d):(d==0?abs(c):gcd(c,d)));

g = a==0&& bc==0?0:(a==0?abs(bc):(bc==0?abs(a):gcd(a,bc)));
g = ab==0&& cd==0?0:(ab==0?abs(cd):(cd==0?abs(ab):gcd(ab,cd)));

than to write your last post. thoughtful