JavaScript prototype to find twin primes

When 2 prime numbers are subtracted and their result is 2 then they are known as twin primes.

Here is the JavaScript prototype to find twin primes up to a given limit. Here is the code snippet.


Code (Run Code):

arr = [];

function checkPrime(num) {
if (num == 1) {
return false;
} else if (num == 2) {
return true;
}

for (var x = 2; x < num; x++) {
if (num % x == 0) {
return false;
}
}
return true;
}

function primeNumbers() {
num = Number(document.getElementById('number').value);
for (var j = 1; j < num; j++) {
if (checkPrime(j)) {
arr.push(j);
}
}
}

function twinPrimes() {
var text = '';
arr = [];
primeNumbers();
text += 'Prime Numbers:';
text += '<br>' + arr;
text += '<br> Twin Primes:'
for (var i = 0; i < arr.length; i++) {
for (var x = i + 1; x < arr.length; x++) {
if ((arr[i] - arr[x]) == -2) {
text += '<br>' + arr[x] + ' and ' + arr[i];
}
}
}
document.getElementById('result').innerHTML = text;
}

No comments:

Post a Comment

GITEX Dubai Talk by Saion Gupta and Saiasmi Gupta

Good morning, everyone. I'm Saion Gupta, the Founder of 10xCoderKids and the Guinness World Record holder for the youngest computer prog...