Alex Rivera | Logout

Is there a JavaScript function that reduces a fraction

Asked 2011-01-10T22:56:29.020
56

say we have fraction 2/4, it can be reduced to 1/2.

Is there a JavaScript function that can do the reducing?

Edit
Report

1 Answer

105
// Reduce a fraction by finding the Greatest Common Divisor and dividing by it.
function reduce(numerator,denominator){
  var gcd = function gcd(a,b){
    return b ? gcd(b, a%b) : a;
  };
  gcd = gcd(numerator,denominator);
  return [numerator/gcd, denominator/gcd];
}

reduce(2,4);
// [1,2]

reduce(13427,3413358);
// [463,117702]
answered 2011-01-10T23:02:49.763

Your Answer