Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript for循环在计算LCM时给出无限循环错误_Javascript_Algorithm_For Loop_Infinite Loop_Lcm - Fatal编程技术网

Javascript for循环在计算LCM时给出无限循环错误

Javascript for循环在计算LCM时给出无限循环错误,javascript,algorithm,for-loop,infinite-loop,lcm,Javascript,Algorithm,For Loop,Infinite Loop,Lcm,我试图解决的问题是计算给定数字范围的最小公倍数。 数组中提供的数字可以是任意顺序,但附件只有两个数字 我的代码适用于[1,5]、[1,10]、[1,12]对,但一旦我尝试了[1,13],我会得到无限循环错误,答案变得不确定 对于以下代码,预期答案为360360 function smallestCommons(arr){ var a=arr[0]; var b=arr[1]; var start=0; var-end=0; 如果(a它应该是product.length-1,因为reduce返回一

我试图解决的问题是计算给定数字范围的最小公倍数。 数组中提供的数字可以是任意顺序,但附件只有两个数字

我的代码适用于[1,5]、[1,10]、[1,12]对,但一旦我尝试了[1,13],我会得到无限循环错误,答案变得不确定

对于以下代码,预期答案为360360

function smallestCommons(arr){
var a=arr[0];
var b=arr[1];
var start=0;
var-end=0;

如果(a它应该是product.length-1,因为reduce返回一个数组

for(let j=numArray[0];j<=product.length-1;j++) {

你的方法是错误的

什么是1,2,3,4的LCM?它是12,因为它是3x4

您的代码将执行以下操作:

var product  = numArray.reduce((a,b)=>a=a*b); // product will be 24
...
for(let j=numArray[0];j<=product;j++) { // iterate from 1 -> 24
    var count = 0;
    for(let k=0;k<numArray.length; k++) { // iterate from 0 -> 3
  
      if(j%numArray[k]==0) { // consider it a hit if j is divisible by an element
        count++;
      }
    }
    if(count==numArray.length) { // on the 4th "hit"
      return j; // return j which is a number between 1 -> 24
    }
  }
我们通过对每个素因子使用max(cnt)来减少这个集合。 1的最大计数为1。2的最大计数为2。3的最大计数为1。 然后我们得到:2x2x3=12,这就是我们的答案

这需要两个通行证:

  • 首先通过数字数组
  • 第二次通过质数计数映射
  • …我的方式:

    函数isPrime(n)
    {
    如果(n<2)返回false
    for(设x=2;x1;--n)
    {
    如果(n>=nMin&&!(nTab.find(x=>(x%n==0)))nTab.push(n)
    if(isPrime(n))
    {
    nTab.forEach(v=>
    { 
    如果(v%n==0)
    {
    设p=0
    而((v%(n**++p))==0{}
    --p
    如果(!xPow[n])xPow[n]=p
    else xPow[n]=Math.max(xPow[n],p)
    }
    })
    }
    }
    返回Object.entries(xPow).reduce((a[v,p])=>a*(v**p),1)
    }    
    console.log('[1,4]->',smallestCommons([1,4]))
    console.log('[1,5]->',smallestCommons([1,5]))
    console.log('[1,10]->',smallestCommons([1,10]))
    console.log('[1,12]->',smallestCommons([1,12]))
    
    console.log(“[1,13]>”,smallestCommons([1,13]))
    非常感谢Eugen的回复。如果您注意到我的代码中有我正在打印产品。它正在打印一个数字。当我调用产品上的length方法时,我得到了NaN。我似乎不明白的是,我的代码一直工作到[1,12],当我尝试[1,13]时,它就中断了。
    1 -> 1(1)
    2 -> 2(1), 1(1)
    3 -> 3(1), 1(1)
    4 -> 2(2), 1(1)