I am new to JavaScript and in need of assistance with a gcd calculation. I want to find the greatest common divisor for pairs of elements from two arrays.
Essentially, I want to iterate through each element A[i]
in array A and each element B[j]
in array B, calculate the gcd of A[i]
and B[j]
, and display the result in the console. However, my current implementation results in 16 incorrect outputs. I suspect that there is an issue with how Euclid's algorithm is being applied, as the values of A[i]
seem to be getting overwritten unexpectedly. Can anyone provide insight on this matter? Below is the code snippet:
var n = 4;
var A = [2, 5, 6, 7];
var B = [4, 9, 10, 12];
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
while (A[i] != B[j]) {
if (A[i] < B[j]) {
B[j] = B[j] - A[i];
} else {
A[i] = A[i] - B[j];
}
}
console.log(A[i]);
}
}