【问题标题】:Do you know of a computer algorithm to solve the ability to divide without division operators?你知道一种计算机算法来解决没有除法运算符的除法能力吗?
【发布时间】:2018-08-03 21:43:01
【问题描述】:

通过在 JavaScript 中应用计算机科学算法,你能解决以下问题吗?

该函数接受正整数或负整数形式的分子和分母。

您不能使用“*”、“/”或“%”。

function divide(num, denom) {
  // ...
}

divide(6, 2)
divide(-10, 5)
divide(7, 2)
divide(-5, 10)

我很想知道是否有已知的计算机科学算法可以解决这个问题。

【问题讨论】:

  • 对于将其他数均分的数字,这很容易,只需从被除数中重复添加(或减去)除数即可。对于不能均匀除其他数字的数字,我想您可以手动编程长除法(回归到递归加法或减法而不是乘法和除法的函数)
  • 检查The approach implement Divide; 方法:不断从被除数中减去除数,直到被除数小于除数。被除数变成余数,减法的次数变成商。 有效方法:使用位操作来求商。除数和被除数可以写成dividend = quotient * divisor + remainder
  • 最简单的算法是binary long division,其中,正如维基百科所指出的,每个步骤仅包含比较和可能的减法。

标签: javascript algorithm math computer-science


【解决方案1】:

我看到了这个问题,不得不对此进行破解,我已经实现了一个解决方案,它可以将小数位数提高到指定的精度并处理负数,它使用递归方法和一些字符串操作。

// Calculate up to decimal point
const MAX_PRECISION = 6;

function divide(numerator, denominator, answer=0, decimals=MAX_PRECISION) 
{
  // Account for negative numbers
  if ((numerator < 0 || denominator < 0))
  {
     // If both are negative, then we return a positive, otherwise return a negative
     if (numerator < 0 && denominator < 0)
          return  divide(Math.abs(numerator), Math.abs(denominator))
     else return -divide(Math.abs(numerator), Math.abs(denominator));
  }

  // Base case return if evenly divisble or we've reached the specificed percision
  if (numerator == 0 || decimals == 0) return answer;

  // Calculate the decimal places
  if (numerator < denominator)
  {
    // Move the decinal place to the right
    const timesTen = parseInt(numerator + "0");

    // Calcualte decimal places up to the certain percision
    if (decimals == MAX_PRECISION)
         return parseFloat(answer + "." + divide(timesTen, denominator, 0, decimals-1));
    else return answer + "" + divide(timesTen, denominator, 0, decimals-1);
  }

  // Perform the calculations in a tail-recursive manor
  return divide(numerator-denominator, denominator, answer+1, decimals);
}

// Test Cases
console.log(divide(10,  2));
console.log(divide(10, -2));
console.log(divide(-7, -4));
console.log(divide( 1, -2));
console.log(divide(11,  3));
console.log(divide(22,  7));

【讨论】:

    【解决方案2】:

    你可以试试类似的东西:

    function divide(num, denom) {
        var count = 0;
        while (num > 0) {
            num = num - denom
            if (num >= 0) {
                count ++;
            }
        }
        return count;
    }
    

    【讨论】:

    • 如果不能整除怎么办?
    • 我不一定要寻找答案,但更重要的是,已知的计算机算法。
    • @AdamH,它仍然必须返回正确的值。例子;如果值为 5, 5 它必须返回 1。
    • @user10178303 如果值是 13 和 3 怎么办?
    猜你喜欢
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 2012-11-10
    • 2017-01-01
    相关资源
    最近更新 更多