Javascript Prime Factorization代码冻结了大量数字

时间:2017-07-26 12:31:43

标签: javascript primes

我制作了这个非常有效的素数分解程序。唯一的问题是,当输入数字很大时,它会冻结浏览器。我的目标是让整个计算持续更长时间,而不是冻结浏览器。我已经尝试了几种方法来解决这个问题。首先我尝试使用async + await sleep(ms)(我在for循环中输入等待睡眠,因为我认为它们导致过度计算问题)但是由于某些未知原因它没有给出回答一下。我还尝试将函数拆分为三个较小的函数(每个for循环一个),并为每个函数使用setTimeout,这也不起作用。我知道,那里可能还有更简单的素数因子分解程序,但是我想在这个程序上工作,因为我自己想出来了。顺便说一句,第一个被调用的函数是factor1(num)

function factor1(num) {
    if (primecheck(num)){
        document.getElementById("resultingz").innerHTML = num + " is prime";
    }else{
        var finalito = [];
        factor2(num, finalito);
    document.getElementById("resultingz").innerHTML = finalito.toString();
    }
}

function factor2(num, arrada){
    var factors = [];
    var factornums = [];

        for (coun = 2; coun <= num/2; coun++) {
            if (num % coun == 0) factornums.push(coun);

        }

        for (i=0; i < factornums.length; i++){
            if (primecheck(factornums[i])){
                factors.push(factornums[i]);
            }
        }
        for (i = 0; i < factors.length; i++){
            rightnow = factors[i];
            while (num % rightnow == 0) {
                arrada.push(factors[i]);
                rightnow = rightnow * factors[i];
            }
        }

    }   

function primecheck(num){
    var primestate = true;
    for (coun = 2; coun <= Math.sqrt(num); coun++) {
            if (num % coun == 0) primestate = false;
        }
        return primestate;
}

1 个答案:

答案 0 :(得分:0)

一些改进:

function factor2(num, arrada){
    for (coun = 2; coun <= num/2; coun++) {//one loop instead of three
        if (num % coun == 0 && primecheck(coun)){
          var rightnow=coun;
          while (num % rightnow == 0) {
            arrada.push(coun);
            rightnow = rightnow * coun;
          }
        }
    }
}   

function primecheck(num){
   var primestate = true,num=Math.sqrt(num);//performance improvement
   for (var coun = 2; coun <=num; coun++) {
        if (num % coun == 0){
         primestate = false;
         break;//stop loop if false found
       }
    }
    return primestate;
}

如果替换一个简单的for循环,你可以轻松地异步循环:

for(var counter=start;counter<max;counter++){
 code;
}
end();

使用伪递归函数:

(function iterate (counter){
  if(counter>=max) return end();//end is a callback

  code;

 setTimeout(iterate,0,counter+1);//next tick, continue with counter+1
})(start);//start the function with a start value