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

Coding for Kids

What is coding? In coding we build a program to do a specific task for us. Code: A code is a set of computer instructions and when you will ...