donchuan
donchuan

Reputation: 95

Calculating the GCD for elements in the arrays; JavaScript

I am just starting with JS and need some help with calculating a gcd. I would like to calculate the gcd for every combination of two elements from two arrays.

I mean: for each element A[i] from array A, for each element B[j] from B, calculate the gcd value of A[i] and B[j] and print it in the console. I do have 16 prints, but they are not correct. I use Euclid's algorithm to calculate it and it looks like the A[i] value is overwritten. I have no idea why. Could someone help me? This is my code:

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]);
  }
}

Upvotes: 1

Views: 2539

Answers (2)

Tempestas Ludi
Tempestas Ludi

Reputation: 1165

You are modifying your array elements while performing euclid's algorithm. I recommend creating a separate function for this algorithm, like:

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++) {
        console.log(euclid(A[i], B[j]));
    }
}

function euclid(a, b) {
    while (b != 0) {
        var r = a % b;
        a = b;
        b = r;
    }
    return a;
}

Edit: You can make and use a storage array in the following way:

var C = []; // The array that will contain the arrays

for (var i = 0; i < n; i++) {
    C[i] = []; // "Inner array"
    for (var j = 0; j < n; j++) {
        C[i][j] = euclid(A[i], B[j]);
        console.log(C[i][j]);
    }
}

Upvotes: 1

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93183

Without complicationg your algorithm , use forEach as following :

const A = [2, 5, 6, 7];
const B = [4, 9, 10, 12];

const gcd = (x, y) => (!y) ? x : gcd(y, (x % y)); 

A.forEach((a, i) => {
 
   B.forEach((b, j) => {
     console.log(
      `GCD(A[${i}]=${a}, B[${j}]=${b}) =`, gcd(a, b)
     );
   });

})

Upvotes: 1

Related Questions