Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a JavaScript function that reduces a fraction

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

Is there a JavaScript function that can do the reducing?

like image 781
dave Avatar asked Jan 10 '11 22:01

dave


People also ask

Can you use fractions in JavaScript?

Fractions don't exist in JavaScript, but you can rewrite them as division problems using the division operator. Note that the resulting number is always converted to decimals — just like with a calculator. Improper fractions use the division operator in the same way.


2 Answers

// 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] 
like image 111
Phrogz Avatar answered Sep 27 '22 21:09

Phrogz


No, but you can write one yourself fairly easily. Essentially you need to divide the top and bottom parts of the fraction by their 'Greatest Common Denominator'... Which you can calculate from Euclid's algorithm.

Read here for more info: http://www.jimloy.com/number/euclids.htm

edit:

code (because everyone seems to be doing it, this doesn't use recursion though)

var FractionReduce = (function(){     //Euclid's Algorithm     var getGCD = function(n, d){         var numerator = (n<d)?n:d;         var denominator = (n<d)?d:n;                 var remainder = numerator;         var lastRemainder = numerator;          while (true){             lastRemainder = remainder;             remainder = denominator % numerator;             if (remainder === 0){                 break;             }             denominator = numerator;             numerator = remainder;         }         if(lastRemainder){             return lastRemainder;         }     };      var reduce = function(n, d){         var gcd = getGCD(n, d);          return [n/gcd, d/gcd];     };      return {             getGCD:getGCD,             reduce:reduce            };  }());  alert(FractionReduce.reduce(3413358, 13427)); 
like image 45
david Avatar answered Sep 27 '22 21:09

david