You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何求解负数的乘法因数?解决JS函数栈溢出问题

负数乘法因数求解与调用栈溢出问题解决

问题说明

原JavaScript函数仅支持正数的因数求解,传入负数时会触发maximum call stack size exceeded(调用栈溢出)错误。原因是原函数始终生成正数进行乘法尝试,而正数的乘积永远不可能等于负数,导致递归无限调用,最终耗尽调用栈空间。

原错误代码

function factorMul(num) {

  let tryThis1 = Math.floor(

    Math.random() * (num - 1 + 1) + 1

  )

  let tryThis2 = Math.floor(

    Math.random() * (num - 1 + 1) + 1

  )

  if(Math.floor(tryThis1 * tryThis2) !== num) return factorMul(num)

  return [tryThis1, tryThis2]

}

解决方案

基于负数因数的特性:负数的有效因数对必然包含一个正数和一个负数。处理逻辑为:先求解目标负数的绝对值(正数)的因数对,再随机将其中一个因数转为负数,即可得到负数的合法因数对。

修改后可处理负数的代码

function factorMul(num) {
  if(String(num).startsWith('-')) {
    let positive = parseInt(String(num).replaceAll('-', ''))
    let factors = factorMul(positive)

    let change = Math.floor(
      Math.random() * (2 - 1 + 1) + 1
    )-1
      
    factors[change] = parseInt("-"+factors[change])

    return factors
  }
  
  let tryThis1 = Math.floor(
    Math.random() * (num - 0 + 1) + 1
  )
  let tryThis2 = Math.floor(
    Math.random() * (num - 0 + 1) + 1
  )

  if(Math.floor(tryThis1 * tryThis2) !== num) {
    return factorMul(num)
  }

  return [tryThis1, tryThis2]
}

内容的提问来源于stack exchange,提问作者Filipino ako

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:55:18