Is there a JavaScript function that reduces a fraction

前端 未结 6 496
小鲜肉
小鲜肉 2020-12-02 12:08

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

Is there a JavaScript function that can do the reducing?

6条回答
  •  遥遥无期
    2020-12-02 12:57

    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

提交回复
热议问题