我的简化分数的程序正在达到调用堆栈限制。为什么?

时间:2016-07-27 16:54:52

标签: javascript node.js

我正在尝试在node.js上的reddit上做简单的日常程序员。链接:https://www.reddit.com/r/dailyprogrammer/comments/4uhqdb/20160725_challenge_277_easy_simplifying_fractions/

我写了一个快速的程序,但它的输出有点不同而且打破了更高的输出。

我的代码:

const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function gcd(a, b) {
  if (b == 0) {
    return a;
  }

  return gcd(b, a & b);
}

function all() {
  rl.question("wewe? ", (answer) => {
    if (answer === "x") {
      rl.close();
      return;
    }
    var str = answer.split(" ");
    var num = +str[0];
    var den = +str[1];
    var div = gcd(num, den);
    console.log(num / div + " " + den / div);
    all();
  });
}

all();

这是当前的输出:

aria@aria-ubuntu /development/randomcode/dailyprogramming$ node Simplifying\ fractions.js
wewe? 4 8
0.5 1
wewe? 1536 78360
readline.js:924
            throw err;
            ^

RangeError: Maximum call stack size exceeded
    at gcd (/development/randomcode/dailyprogramming/Simplifying fractions.js:7:13)
    at gcd (/development/randomcode/dailyprogramming/Simplifying fractions.js:12:10)
    at gcd (/development/randomcode/dailyprogramming/Simplifying fractions.js:12:10)
    at gcd (/development/randomcode/dailyprogramming/Simplifying fractions.js:12:10)
    at gcd (/development/randomcode/dailyprogramming/Simplifying fractions.js:12:10)
    at gcd (/development/randomcode/dailyprogramming/Simplifying fractions.js:12:10)
    at gcd (/development/randomcode/dailyprogramming/Simplifying fractions.js:12:10)
    at gcd (/development/randomcode/dailyprogramming/Simplifying fractions.js:12:10)
    at gcd (/development/randomcode/dailyprogramming/Simplifying fractions.js:12:10)
    at gcd (/development/randomcode/dailyprogramming/Simplifying fractions.js:12:10)

预期产出:

1 2
64 3265

1 个答案:

答案 0 :(得分:0)

这是一个简单的错误!该死的我的新键盘。我不敢相信我这样做了。

我使用了4& 8当它应该是4%8时。