是否有一个 JavaScript 函数可以减少一个分数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4652468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:26:14  来源:igfitidea点击:

Is there a JavaScript function that reduces a fraction

javascriptfunctionfractions

提问by dave

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

说我们有分数2/4,它可以减少到1/2

Is there a JavaScript function that can do the reducing?

是否有可以进行还原的 JavaScript 函数?

回答by Phrogz

// 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]

回答by david

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

阅读此处了解更多信息: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));

回答by Larry Battle

To reduce a fraction, divide the numerator and denominator by the Greatest Common Factor. Phrogz and David have already provided the source code..

要减少分数,请将分子和分母除以最大公因数。Phrogz 和 David 已经提供了源代码。

However if you're searching for javascript libraries for handling fractions, then here are a few to choose from.

但是,如果您正在搜索用于处理分数的 javascript 库,那么这里有一些可供选择。

  1. Fraction.js
  2. Math.Rational
  3. Ratio.js
  4. Rational.js
  1. 分数.js
  2. 数学理性
  3. Ratio.js
  4. Rational.js

Here's an example using Ratio.js.

这是一个使用Ratio.js的示例。

var a = Ratio(2,4);

a.toString() == "2/4";
a.simplify().toString() == "1/2";    // reduce() returns a clone of the Ratio()
a.toString() == "2/4"; // Ratio functions are non-destructive.

回答by Jabel Márquez

I know there is already an answer, but I want share a JS library that I found when I was looking something to convert decimal numbers into fractionsand reducing fractions.

我知道已经有答案了,但我想分享一个 JS 库,我在寻找将十进制数转换为分数减少分数时发现的

The library calls Fraction.js, which was really helpful for me and saved me a lot time and work. Hope it can be very useful to somebody else!

该库调用Fraction.js,这对我真的很有帮助,并为我节省了很多时间和工作。希望它可以对其他人非常有用!

回答by RetroCoder

Here is a recursive function using ECMAScript 6 reduce. It works for most fractions as long as the remainder isn't too small. 0 has been redefined to make it work for arrays like [1.2, 2.4, 12, 24]. I tested in Chrome and IE Edge so it may behave differently in other browsers or upgrades. So it should work with an array of floats.

这是一个使用 ECMAScript 6 reduce 的递归函数。只要余数不是太小,它适用于大多数分数。0 已被重新定义,使其适用于 [1.2, 2.4, 12, 24] 等数组。我在 Chrome 和 IE Edge 中进行了测试,因此它在其他浏览器或升级中的行为可能有所不同。所以它应该与一组浮点数一起工作。

 Array.prototype.gcd = function () {
   if (this.length === 0)
     return null;
   return this.reduce((prev, curr) => {
     if (curr <= 1.00000000001e-12)
       return prev
     else
       return [curr, prev % curr].gcd();
    });
  }

  var reducedValueGCD = [1.2, 2.4, 12, 24, 240].gcd();

Search for MDN reduce or more info here.

在此处搜索 MDN reduce 或更多信息。

回答by SoEzPz

Reduce a string fraction like "2/4" and output as string fraction.

减少像“2/4”这样的字符串分数并输出为字符串分数。

function reduce([numerator, denominator]){
  for (let i = numerator; i > 0; i--) {
    if(!(numerator % i) && !(denominator % i)){
      return [(numerator / i), (denominator / i)];
    }
  }
}

function reduceFraction(string){
  return reduce(string.split('/').map(n => +n)).join('/');
}

one = '2/4';
two = '20/200';
three = '330/2050';

console.log('2/4 reduced to', reduceFraction(one));
console.log('20/200 reduced to', reduceFraction(two));
console.log('330/2050 reduced to', reduceFraction(three));