只能用减法递归除法——不能处理小数

Dividing recursively with only subtraction --- not being able to handle decimals

本文关键字:不能 处理 小数 除法 递归      更新时间:2023-09-26

我正在练习我的数学/算法技能,我正试图用减法除两个数字。我很接近了,但我好像不懂小数,我不知道为什么?在堆栈的最底层,当我调用divide(9,2)时,我注意到我返回的是"0",而实际上我想返回1/2 -但没有使用除法运算符…在if x小于y检查中,我应该在子程序中添加这个逻辑吗?我被如何递归地把小数点后的数字加到三位卡住了。

    var divide = function(x, y) {
        //the number of times you need to subtract y from x.
      if (y === 0) {
        return 0
      } 
      // if 
      if (x - y === 0) {
        return 1;
      } 
      if (x < y) {
    // if this is the case, get the value of y - x.  ->1
    var diff = y - x;
    console.log(diff);
    // add a zero to the end --> so in our case, 10
    diff = String(diff) + '0';
    console.log(diff);
    diff = Number(diff);
    console.log(diff);
    // is that now divisible by y? is so how many times? in our case, 5 times.
    var decimal = Number(divide(diff, y));
    var number = "." + decimal;
    //so add .5 to it.
    return number;
  } else {
        return (1 + divide(x - y, y)); 
      }
    };
    var modulo = function(x, y) {
      var val = x;
      while (val >= y) {
        val -= y;
      }
      return val;
    };

你认为这是作弊吗?没有除法和乘法,加法变成了减法,它返回一个浮点数,并且使用递归。但是,有相当数量的字符串转换正在进行,以连接数字并添加符号和小数点。

function divide(x, y, prec) {
    if (y == 0) return NaN;
    var quot = 0, sign = 1;
    if (x < 0) { 
        sign = 0 - sign;
        x = 0 - x;
    }
    if (y < 0) {
        sign = 0 - sign;
        y = 0 - y;
    }
    while (x >= y) {
        x -= y;
        quot = 0 - (0 - 1 - quot);
    }
    quot = (sign < 0 ? "-" : "").concat(quot, prec == undefined && x > 0 ? "." : "");
    if (x > 0) {
        prec = prec || 13;
        if (--prec) {
            for (var i = 9, temp = x; i; i--) x = 0 - (0 - x - temp);
            quot = quot.concat(divide(x, y, prec));
        }
    }
    return parseFloat(quot);
}
alert(divide( 9,  2));
alert(divide( 2,  9));
alert(divide( 9, -2));
alert(divide(-2,  9));
alert(divide(-9, -2));
alert(divide( 0,  9));
alert(divide( 9,  0));

这是因为当x小于y时,您将返回0。然而,这正是奇数除以2的结果——在最后一步中,算法将尝试用1除以2。在这种情况下,您需要实现逻辑,而不是简单地返回0。

如果你不反对浮点错误,这将做的技巧,而不是/, *甚至+的视线。
您可以设置精度,但如果再多几个数字,它就会变得非常慢。

它的工作原理是设置商为x,然后反复从x中去除y个小部分,从商中去除y-1个小部分,直到x为0,商为x/y。

function divide(x, y) {
    var sign = x < 0 ^ y < 0 ? -1 : 1;
    x = y ? (x > 0 ? x : 0 - x) : -1; y = y > 0 ? y : 0 - y;
    var quot = x, prec = 0.000001;
    while (x > 0) for (var i = y - 1, x = x - prec; i; i--, x -= prec, quot -= prec);
    return y ? (sign > 0 ? quot : 0 - quot) : NaN;
}
alert(divide( 9,  2));
alert(divide( 2,  9));
alert(divide( 9, -2));
alert(divide(-2,  9));
alert(divide(-9, -2));
alert(divide( 0,  9));
alert(divide( 2,  0));