= 2 , m=begin number-6ren">
gpt4 book ai didi

javascript - Codewars的"Steps in Primes"

转载 作者:行者123 更新时间:2023-11-28 06:36:46 25 4
gpt4 key购买 nike

我在进行 Codewars 的“Steps in Primes”时遇到了问题。

Make function step(g,m,n) which g=step >= 2 , m=begin number >=2, n=last number>= n. Step(g,m,n) will return the first match [a,b] which m < a,b is prime < n and a+g=b.

我在基本测试用例中做得正确,但是当我提交时,我在某处遇到了无限循环。有人可以给我建议吗?

function isInt(n) {
if(typeof n==='number' && (n%1)===0) {
return true;
}
else return false;
}
function step(g, m, n) {
if(isInt(g) && isInt(m) && isInt(n) &&g >= 2 && m >= 2 && n>=m) {
var p=[];
var ans=[];
for (var temp=m; temp<=n;temp++)
{
var a=0;
for (var chk=2; chk<temp-1;chk++)
if (temp%chk===0) a++;
if (a===0) p.push(temp);
}
for (var a=0;a<p.length-1;a++)
{
for (var b=a+1;b<p.length;b++)
if (p[b]===(p[a]+g)) return [p[a],p[b]];
}
}
return "nil";
}

最佳答案

这段代码可能对你有帮助

   function gap(g, m, n) {
var prime-numbers = [];
var final = [];
var prime;

for (var i = m; i <= n; i++) {
prime = true;
for (var j = 2; j < i / 2; j++) {
if (i % j === 0) {
prime = false;
}
}
if (prime) {
prime-numbers.push(i);
}
}

prime-numbers.forEach(function(prime, index) {
if (prime + g === prime-numbers[index + 1]) {
final.push(prime, prime-numbers[index + 1]);
}
});

if (final) return final.slice(0,2);
else return null;
}

关于javascript - Codewars的"Steps in Primes",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34210631/

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