1

I got problems when doing "Steps in Primes" of Codewars.

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.

I did right in basic test cases but when i submit , i got infinity loop somewhere. Can anyone give me suggestion?

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";
}
Mr_Pouet
  • 4,061
  • 8
  • 36
  • 47
  • I don't think you truly have an infinite loop, but your prime test is of quadratic complexity, which will start to take a noticeable amount of time if n-m gets too large. Take a look here for pointers on a more efficient way: http://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking-if-a-number-is-prime – jeff carey Dec 10 '15 at 21:22
  • I just finish the task. I redo the code all, the workflow is right but it takes tons of time for huge test case of Codewars. I wont spoil the answer here but if someone meet same problem so try to improve check Prime solutions, as less as possible and also scan the these "possible Prime" in smarter way. – Trung Hoang Dec 10 '15 at 22:37

1 Answers1

0

this code might help you

   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;
}