JavaScript prototype to find co-primes

Co-primes are numbers whose common factor is only 1. For example :- 4, 9
Factors of 4 :- 2, 2, 1
Factors of 9 :- 3, 3, 1
Common Factor :- 1

Here is the JavaScript prototype to find co-primes. Here is the code snippet.


Code (
Run Code):

function factors(num) {
arr = [];
for (var i = 1; i < num; i++) {
if (num % i == 0) {
arr.push(i);
}
}
return arr;
}

function coPrime(num1, num2) {
arr1 = factors(num1);
arr2 = factors(num2);
for (var i = 1; i < arr1.length; i++) {
for (var j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
return num1 + ' and ' + num2 + ' are not co-prime';
}
}
}
return num1 + ' and ' + num2 + ' are co-prime';
}

function main() {
document.getElementById('result').innerHTML =
(coPrime(document.getElementById('num1').value, document.getElementById('num2').value))
}

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 ...