I wrote JavaScript code for finding the first two consecutive prime numbers (that doesn't have divisors except one and itself) with a specific gap between them. It works well but take too much time to give results for large numbers.
When I tested this, it took about 48s to give the result:
gap = 8 ,start = 3,000,000 and end = 4,000,000
I read about how to cache to minimize access for properties as length and put variables in local scope to make the code more efficient, but it didn't help me a lot. I then tried to optimize the for loops, but it affects the functionality of the code.
function gap(gap, start, end){
var arr = [];
var counter = [];
var result;
for(var x = start; x <= end; x++){
if(x % 2 == 1){
arr.push(x)
}
}
for(var cache = arr.length, j = cache ; j >= 0; j--){
for(var i = 2; i <= Math.sqrt(arr[j]); i++){
if(arr[j] % i === 0){
if(i != arr[j]/i || i * i == arr[j]){
counter.push(arr[j] / i)
arr.splice(j, 1)
break;
}
}
}
if((arr[j+1] - arr[j]) == gap){
result = [arr[j], arr[j+1]]
}else if (result == undefined){
result = null
}
}
return result
}