gpt4 book ai didi

Javascript 质因数分解代码因大量数字而卡住

转载 作者:行者123 更新时间:2023-11-28 04:22:36 24 4
gpt4 key购买 nike

我制作的这个质因数分解程序运行得非常好。唯一的问题是,当输入很大时,它会卡住浏览器。我的目标是让整个计算持续更长时间,而不是卡住浏览器。我尝试了几种方法来解决这个问题。首先,我尝试使用async + await sleep(ms)(我在for循环中输入await sleep,因为我认为它们导致了过度计算问题)但是由于某种未知的原因,它根本没有给出答案。我还尝试将函数拆分为三个较小的函数(每个 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;
}

最佳答案

一些改进:

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

关于Javascript 质因数分解代码因大量数字而卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45327089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com