Finding the least common multiple (LCM) of two or three numbers using JavaScript

I have been working on a code snippet to find the Greatest Common Denominator (GCD) of two or three numbers. Here is what I have so far:

Math.GCD = function(numbers) {
  for (var i = 1 ; i < numbers.length ; i++){
    if (numbers[i] || numbers[i] === 0)
      numbers[0] = twogcd(numbers[0], numbers[i]);
  }
  return numbers[0];

  function twogcd(first, second) {
    if (first < 0) first = -first;
    if (second < 0) second = -second;
    if (second > first) {var temp = first; first = second; second = temp;}
    while (true) {
        first %= second;
        if (first == 0) return second;
        second %= first;
        if (second == 0) return first;
    }
   }
};

Math.LCM = function(first,second) {
    return first * (second / this.GCD(first, second)); // STRUGGLING TO EXTEND THIS TO THREE #s
};

// example
console.log(Math.GCD([4, 5, 10]));
Check out the live example on JSFiddle

Take note of the part in the code related to the Least Common Multiple (LCM)

I am currently attempting to expand this functionality to calculate the LCM of either two or three user-inputted values. Unfortunately, I'm having trouble getting it right. As an amateur in JavaScript, any assistance would be greatly appreciated. Remember that if a value is left empty, it should not be included in the computation similarly to how it's done with the GCD.

Answer №1

If you're looking to find the greatest common divisor or least common multiple of a list of integers, here are some useful functions:

function findGCD(a, b) {
  // Find the greatest common divisor of two integers
  if(!b) return b===0 ? a : NaN;
  return findGCD(b, a%b);
}
function findGCDFromArray(array) {
  // Find the greatest common divisor of an array of integers
  var result = 0;
  for(var i=0; i<array.length; ++i)
    result = findGCD(array[i], result);
  return result;
}
function findLCM(a, b) {
  // Find the least common multiple of two integers
  return a*b / findGCD(a, b);
}
function findLCMFromArray(array) {
  // Find the least common multiple of an array of integers
  var result = 1;
  for(var i=0; i<array.length; ++i)
    result = findLCM(array[i], result);
  return result;
}

Answer №2

If you tweak the structure slightly for GCD and LCM, both methods can be streamlined to have just two arguments.

To calculate the result for more than two arguments, utilize Array.prototype.reduce(). This method selects two elements from the array at a time and returns a result, which is then incorporated as a new input until all array elements are processed.

Given that LCM and GCD adhere to the associative property, they can be linked together as needed.

Math.GCD = function twogcd(first, second) {
    if (first < 0) first = -first;
    if (second < 0) second = -second;
    if (second > first) { var temp = first; first = second; second = temp; }
    while (true) {
        first %= second;
        if (first == 0) return second;
        second %= first;
        if (second == 0) return first;
    }
};

Math.LCM = function (first, second) {
    return first * (second / Math.GCD(first, second));
};

document.getElementById('calc').addEventListener('click', function (e) {
    var first = +document.getElementById("first").value,
        second = +document.getElementById("second").value,
        third = +document.getElementById("third").value,
        numbers = [first, second, third],
        resultGCD = numbers.reduce(Math.GCD), // chaining
        resultLCM = numbers.reduce(Math.LCM); // chaining

    document.getElementById('gcd').innerHTML = resultGCD;
    document.getElementById('lcm').innerHTML = resultLCM;
});
GCD: <span id="gcd"></span><br />
LCM: <span id="lcm"></span><br />
<form name="sci-calc" method="POST" id="sci-calc">
    <input type="text" name="stuff[]" class="input-field" id="first" /><br />
    <input type="text" name="stuff[]" class="input-field" id="second" /><br />
    <input type="text" name="stuff[]" class="input-field" id="third" /><br />
    <button type="button" id="calc">CALC</button>
</form>

Answer №3

I haven't quite deciphered the purpose of your code, but I have a function here that can help find the LCM:

LCM = function(numbers) {
  console.log(numbers)  
  if (numbers.length < 2) return
  first = numbers[0]
  second = numbers[1]
  var i = j = 1
  var mult1 = first * i++
  var mult2 = second * j++
  while (mult1 != mult2) {
    if (mult1 < mult2)
        mult1 = first * i++
    else
        mult2 = second * j++
  }
  if (numbers.length > 2) {
    numbers[1] = mult1 //It may modify 'numbers' 
    mult1 = LCM(numbers.splice(1, numbers.length-1))
  }
    return mult1
}

It may not be the most efficient solution, but it demonstrates how you can handle multiple parameters using recursion.

You can see it in action on this fiddle: https://jsfiddle.net/grabantot/fr0gzogL/

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 are the best methods for testing REST API and Client-side MVC applications?

When dealing with a RESTful server that only responds with JSON data fetched from a database, and having a client-side application like Backbone, Ember or Angular, where should application testing take place? Is it necessary to have two sets of tests - on ...

Sending an identifier to a PHP file using JavaScript

I am facing an issue with my JavaScript code where the id is supposed to be passed to my PHP script at intervals, but if the id stops being passed (indicating that the user has closed the JavaScript page), a specific block in the if statement should run in ...

How can I showcase an image from the search results using the Giphy API?

Find the GitHub link to the Giphy API here: https://github.com/Giphy/GiphyAPI. As a newcomer, I'm facing a roadblock. Currently, I am receiving random gifs from the Giphy API instead of the specific search result requested by the user. Is there a wa ...

The depth buffer in Webgl FrameBuffer is not being cleared properly

Currently, I am working on developing a 2D sprite renderer that utilizes render textures for custom compositing. However, I have encountered an issue where the depth buffer on the FrameBuffer is not clearing properly. Due to this, all the sprites leave a p ...

I am facing an issue with resolving services in my AngularJS controller

Having trouble resolving the service data in AngularJS controller. var kattaApp = angular.module('kattaApp', []).controller('kattaController', function($scope, dataFactory) { var promise = dataFactory.getResult().then(function(data ...

How can I replicate the function of closing a tab or instance in a web browser using Protractor/Selenium?

I want to create an automated scenario where a User is prompted with an alert message when they try to close the browser's tab or the browser itself. The alert should say something like "Are you sure you want to leave?" When I manually close the tab ...

Achieving compatibility with pseudo elements :before/:after in Internet Explorer 7

I've been attempting to make these functionalities compatible with IE 7, but I'm encountering difficulties. I've downloaded and included the jQuery plugin for it in the header as shown below: <!--[if lte IE 7]> <script type="text/j ...

Processing JSON data from an array in PHP

Currently, my code involves utilizing an AJAX request to retrieve data from a database dynamically. The data received is processed by the PHP function json_encode() before being sent back to AJAX. Upon receiving the data through the AJAX request, it is for ...

"X-Requested-With" header not being included in XMLHttpRequest request

After successfully using jQuery.ajax() to make an ajax call to an MVC action, I decided to switch to using the XMLHttpRequest along with the HTML5 File API due to some forms containing file controls. However, since making this change, the MVC action no lon ...

"Employing regular expressions to extract the name of the web browser

Experiencing issues with regular expressions in JavaScript. Attempting to extract the version number and browser name, such as "Firefox 22.0" or "MSIE 8.0". console.log(navigatorSaysWhat()) function navigatorSaysWhat() { var rexp = new RegExp(/(firefox ...

Using AJAX and JavaScript to enhance a form before submitting it

As a PHP developer delving deeper into AJAX, I have encountered a perplexing issue that I need help resolving. I am dynamically generating a form like so: function addSearchResult(label, tz) { var html = ''; html += '<div>&ap ...

Using Vue.js to invoke an external JavaScript function for search functionality

In my vue.js application, I have a list of users with backend pagination. Now I want to implement a search functionality. I attempted to call the method like this: watch: { search: function() { Crud.methods.getItems(); } }, Howe ...

Issues have been observed with the functionality of the Node.js EventEmitter when attempting to

Here's the issue: I have a class called save.js that inherits from EventEmitter. Here's how it looks: var util = require('util'); var EventEmitter = require('events').EventEmitter; var save = function(pdf){ var ...

Infinite error loop during start-up in AngularJS application due to digest cycle overflow

Just starting out with Angular and working on a new project using node, jade, and angular. I'm having trouble implementing a catch-all server route. Every time the index page loads, it gets stuck in a loop and crashes the app. I've tried several ...

Choosing an option in Vue using select, v-for loop, and v-model

How can I set a preselected option in a select element using v-model, v-for for options, and an object as the value? The options are elements with unique ids, and I want to preselect based on custom equality (e.g., matching the id field). Is there a way to ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

Alert displayed on console during transition from MaterialUI lab

Whenever I try to run my MUI application, an error pops up in the console It seems you may have forgotten to include the ref parameter in your forwardRef render function. import { LoadingButton } from "@mui/lab"; const LoadData = ({loading,sig ...

The alias for the last item in a nested ng-repeat loop will consistently evaluate to true

Within my code, I am utilizing two nested ng-repeat functions and I am looking to change the $last variable to something different for each level - let's say outerLast and innerLast. I attempted to achieve this by using ng-init="outerLast= $last" and ...

What could be causing jQuery to successfully animate the size of my div element but not the color of my text?

My jQuery code successfully animates the height and width of divs, but it doesn't seem to be working for the text color within those divs. I'm not sure what I'm missing here. Below is the full code snippet, with lines 9 and 12 being the ones ...

Collaborative session sharing between two node applications through Single Sign-On (SSO

I currently have a website created with express and node.js. I need to add a nodebb forum to this website, which is a separate node application. Both the main site and the forum use Facebook login, but users have to log in separately using the same Faceboo ...