LarryBattle / Ratio.js

Rational numbers for Javascript
http://larrybattle.github.com/Ratio.js/
MIT License
113 stars 9 forks source link

Bug in `Ratio.gcd()` #51

Closed LarryBattle closed 10 years ago

LarryBattle commented 11 years ago

For gcd(a,b), if b == 0 then a should be returned.

Testcase

equal(10, gcd(10,0));
equal(10, gcd(0,10));
equal(5, gcd(200,15));
equal(5, gcd(200,55));
equal(50, gcd(200,50));
equal(2, gcd(2,50));
equal(1, gcd(2,5));

Easy fix:

Ratio.gcd = function (a, b) {
          var c;
                a = +a;
                b = +b;
                if(isNaN(a) || isNaN(b)){
                    return NaN;
                }
          if(b === 0){
            return a;
          }
          while (b) {
              c = a % b;
              a = b;
              b = c;
          }
          return a;
      }

Reference: http://en.wikipedia.org/wiki/Euclidean_algorithm

LarryBattle commented 10 years ago

The pull request https://github.com/LarryBattle/Ratio.js/pull/69 fixes this issue.