奇数返回2作为主要因子

时间:2018-07-30 14:01:54

标签: javascript recursion numbers

此函数接受一个数字,并以数组形式返回其主要因子。我运行了一堆测试用例,除了这个数字90000004000000001之外,其他所有测试用例都正确无误。

该代码根本没有优化,因此大多数大数字都会超时。但是,这个测试用例出于某种原因进行了计算,它给了我[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 89, 241, 1049]的因素,这显然是毫无意义的,因为90000004000000001是一个奇数。

将因子相乘时,得出的数字为90000004000000000。比原始号码低1

这很奇怪,所以我尝试了90000004000000001 % 2并返回0

我开始认为我的函数可能不是问题,而是javascript中的模数或数字。在这种情况下,偶数如何被2整除?

我把一些测试用例作为控制台日志以及代码片段,以便您可以看到结果。

谢谢!

// Assuming it works will factor an integer into its prime components and return them as an array
function factorize(num) {
  num = Math.floor(num);

  // the array to store all factors
  let factors = [];

  // goes through all numbers starting at 2
  // break when a factor is found
  // will also break if num is prime (its own factor)
  let i = 2;
  while (true) {
    if (num % i === 0) {
      factors.push(i);
      break;
    }
    i++
  }

  // i is the factor from the while loop
  // if num is not prime recursively factorize the remainder after factoring out i
  if (i !== num) {
    factors = factors.concat(factorize(num / i));
  }

  return factors;
}


console.log(factorize(16)); //[2, 2, 2, 2]
console.log(factorize(101)); //[101]
console.log(factorize(100001)); //[11, 9091]
console.log(factorize(141)); //[3, 47]
console.log(factorize(90000004000000001)); //[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 89, 241, 1049]
console.log(factorize(90000004000000001).reduce((a, b) => a * b)); //90000004000000000

1 个答案:

答案 0 :(得分:0)

您的数字大于可以精确存储在Javascript数字值Number.MAX_SAFE_INTEGER中的最大整数,该值的值为9007199254740991,即(2 ^ 53)-1。

用2的幂表示,您的数字大约等于2 ^ 56.32077,所以它有3.32个太多的“位”无法准确表示,这意味着在其中的任何值都会有±10左右的误差这个范围。

这是IEEE 754双精度浮点格式的局限性。

因此,不可能对其执行精确的整数运算。

只是为了好玩,请在您的JS控制台中尝试以下操作:

> console.log(90000004000000001 + 1)
90000004000000000

> console.log(90000004000000001 + 9)
90000004000000020