Finding the Greatest Common Divisor (GCD) for elements within arrays using JavaScript

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

Answer №1

When implementing euclid's algorithm, it is important to avoid modifying the original array elements directly. Instead, consider encapsulating the algorithm in a separate function like this:

var n = 5;
var X = [3, 8, 9, 11, 15];
var Y = [6, 12, 14, 18, 21];

for (var k = 0; k < n; k++) {
    for (var l = 0; l < n; l++) {
        console.log(findGcd(X[k], Y[l]));
    }
}

function findGcd(x, y) {
    while (y != 0) {
        var remainder = x % y;
        x = y;
        y = remainder;
    }
    return x;
}

Update: To store the results of the computations, you can utilize an additional array structure as demonstrated below:

var Z = []; // Array to hold computed values

for (var k = 0; k < n; k++) {
    Z[k] = []; // Initialize inner arrays
    for (var l = 0; l < n; l++) {
        Z[k][l] = findGcd(X[k], Y[l]);
        console.log(Z[k][l]);
    }
}

Answer №2

To simplify your algorithm, utilize the forEach method in the following way:

const numsA = [4, 8, 12, 16];
const numsB = [7, 14, 21, 28];

const findGCD = (num1, num2) => (!num2) ? num1 : findGCD(num2, (num1 % num2)); 

numsA.forEach((a, i) => {
 
   numsB.forEach((b, j) => {
     console.log(
      `GCD(numsA[${i}]=${a}, numsB[${j}]=${b}) =`, findGCD(a, b)
     );
   });

})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing JavaScript Ajax calls to fail over SSL specifically on IOS devices, with the exception of IOS

I am encountering an issue with a mobile application I have developed. It makes an ajax xmlHttpRequest request over SSL to another application on the same domain in order to authenticate a user. Strangely, this call fails with response code zero on IOS dev ...

Can static global variables in Java be altered within a function without being returned?

private static char[][] grid= new char[10][10]; private static void setHorizontal(String[] words, int i, int r, int c, boolean[] cross) { for (int j = c; j < (c+words[i].length()); j++) { if (grid[r][j] != '-'){ cross[ ...

What is the best way to incorporate external HTML content while ensuring HTML5 compatibility? Exploring the different approaches of using PHP, HTML

While this may seem like a simple task to the experts out there, I have been struggling for over an hour without success... My objective is to use a single footer file and menu file for all my webpages while considering blocking, speed, and other factors. ...

utilizing a Bootstrap modal element throughout multiple HTML documents

I have a bootstrap modal dialog div that I want to use in all 4 html pages of my web application without repeating the code. I have a common JavaScript file for this purpose. What is the best way to achieve this? <!-- Modal --> <div class="modal ...

A guide on cycling through the data within the input fields

Here's my code snippet: <div class="form-group row text-right" *ngFor='let row of vipInput'> <label class="col-sm-3 form-control-label m-t-5" for="password-h-f"></label> <div class="col-sm-9 form-control-label m-t-5 ...

What is the best way to manage error handling in various locations within an Angular stream?

Currently, I am working on ensuring that errors are handled properly in a stream where the id of a group is retrieved first and then used to obtain profile information. I want to easily identify whether the error is occurring during the retrieval of the g ...

Retrieve the value of an array in reactjs based on a specific condition

Here's an array I have: array = [ { period: 1, currency: 1, cost: 100, count: 10 }, { period: 1, currency: 2, cost: 200, count: 10 }, { period: 2, currency: 1, cost: 300, count: 20 }, { period: 3, currency: 3, cost: 400, count: 30 } ] I' ...

increase the selected date in an Angular datepicker by 10 days

I have a datepicker value in the following format: `Fri Mar 01 2021 00:00:00 GMT+0530 (India Standard Time)` My goal is to add 60 days to this date. After performing the addition, the updated value appears as: `Fri Apr 29 2021 00:00:00 GMT+0530 (India St ...

How to Repeat the Initial Element of a PHP Array during Implode操作

$sql = "SELECT * FROM `likes` WHERE `pid` = $pid"; $result = $conn->query($sql); if ($result->num_rows > 0) { $likers = array(); while($row = $result->fetch_assoc()) { $likers[] = $row['uid']; echo implode( ...

Styling and Script Files on a JQuery Mobile Website

Is it necessary to include CSS and JS files in every HTML page for a mobile site developed with JQueryMobile? <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> <script src="http://code.jquery.com/jqu ...

What is the correct way to execute a JavaScript function during the page load event?

Currently, I am utilizing a currency conversion Web Service and I have implemented a Javascript function to display the result upon clicking a button. However, I would like this Javascript function to execute automatically when the page loads. Here is the ...

Enhance user experience with a dynamic Bootstrap combo box that updates based on

I am currently facing an issue with the bootstrap combobox plugin. I am having trouble changing the selection and sending that information from the view to the controller. $('#MyCombo').on('change', function () { var data = $(this) ...

What could be the reason behind npm trying to utilize a package version that is not specified in my package.json file?

My Angular and .NET 5 web application is encountering an issue when trying to install packages using the command npm i. The error message that appears is: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While re ...

Angular allows developers to easily show or hide different elements on a webpage

I have a situation where I need to display date and time within two separate div elements. There are two checkboxes available: 1. Add Additional: This will add one more div for each date and time. 2. Time/Date will be the same: This will add just the date ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

You can only set headers once during the initial request; any additional attempts to set headers will result in an

I encountered a specific issue with the error message "Can't set headers after they are sent". Here is the relevant code snippet: create: (request, response, next) -> socket = @app.socket # # This method will be used to call the right method ins ...

Check to see if a key exists within the entire JSON using jQuery

I'm struggling with checking if a specific key is contained in my JSON data array. I want to add a class or perform an action if the key is present, otherwise do something else. I've tried using inArray and hasOwnProperty but can't seem to g ...

Switch between divs based on the current selection

var header = $("#accordion"); $.each(data, function () { header.append("<a id='Headanchor' href='javascript:toggleDiv($(this));'>" + this.LongName + "</a>" + "<br />", "&l ...

Achieving a transparent inner box-shadow effect on hover: a step-by-step guide

Is there a way to make the black ring transparent upon hover by changing box-shadow: 0 0 0 5px #000, 0 0 0 10px green to box-shadow: 0 0 0 5px transparent, 0 0 0 10px green? It doesn't seem to be working for me. Any suggestions on how to achieve this ...

Alter data in MongoDB based on specific circumstances

Currently, I am utilizing node.js and mongoose for a project. The task at hand involves updating database information only if the required field either does not exist in the database or its value is less than 'x'. Specifically, this pertains to ...