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

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