Does my method need adjustments or is it fundamentally flawed?

<html><head></head>
<body><script>
  function calculateGreatestCommonDivisor(a, b) {
    if (a == 0) {
      return b;
    }
    return calculateGreatestCommonDivisor(b % a, a);
  }

  function getDifference(array) {
    for (var i = Math.min(...array) + 1; i < Math.max(...array); i++) {
      array.push(i);
    }
    array.sort((a, b) => a - b);
  }

  function findSmallestCommonMultiple(arr) {
    getDifference(arr);
    console.log(arr);
    a = arr[arr.length - 1];
    b = arr[arr.length - 2];
    var LCM = a * b / calculateGreatestCommonDivisor(a, b);
    while (true) {
      var index = arr.findIndex(element => LCM % element !== 0);
      if (index === -1) {
        return LCM;
      }
      LCM *= arr[index];
      console.log(LCM);
    }
  }
  findSmallestCommonMultiple([1, 5]) // correct 
  findSmallestCommonMultiple([2, 10]) // correct
  findSmallestCommonMultiple([1, 13]) // incorrect
  findSmallestCommonMultiple([23, 18]) // incorrect
</script></body>
</html>

This code is part of a challenge which can be found at:

Here is the algorithm I am using:

1- Calculate the Least Common Multiple (LCM) of the two greatest numbers in the array.

2- Divide the LCM by each number in the array until you find one that doesn't divide evenly. Multiply that number with LCM and repeat the process until no such number is found. Then return the LCM.

While the code works correctly for the first two arrays, it fails for the last two arrays. I am wondering if my algorithm is fundamentally flawed and needs a complete rewrite or if it just requires some adjustments?

It's important to note that there are three separate functions in the code: one for calculating the Greatest Common Divisor (GCD), another for finding the range of values between two numbers in the array, and the third for calculating the LCM.

The issue arises with the last two arrays:

findSmallestCommonMultiple([1, 13]) returns 4324320 instead of 360360

findSmallestCommonMultiple([23, 18]) returns 72681840 instead of 6056820

Therefore, I am seeking advice on whether my algorithm needs a complete overhaul or if minor tweaks can make it work as intended.

Please refrain from providing ready-made codes and simply offer insights on my specific query. Thank you (:

Answer №1

Your calculation is incorrect when multiplying by arr[index].

Let's rename our variables to make things clearer:

    X = array[index]
    Y = GCD(LCM, X)

Now, we can express X and LCM as:

    X = Y × Z
    LCM = Y × W

In order to ensure that the smallest number is the lowest common multiple of the current LCM and X, you need to calculate it as:

    LCM := Y × Z × W

However, if you calculate it with the provided code snippet:

LCM *= arr[index];

You are actually calculating:

    LCM := (Y × W) × (Y × Z) = Y × Y × Z × W

In other words, you have one extra Y factor. To calculate it correctly, you should use the following code instead:

LCM *= arr[index] / GCD(LCM, arr[index]);

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

Managing data in React using the useState hook

I need assistance in enhancing the state without causing any overwrite. Presently, whenever a new value is added, it replaces the existing array. My objective is to utilize useState and incorporate the form value. import {useState} from 'react'; ...

Tips for customizing the appearance of the day button in a React Material-UI date picker

In my React project, I am using material-ui date picker and I am looking for a way to customize the styling of the day buttons. Specifically, I want to change the text color of the available days. By default, as seen in the screenshot, the text color is bl ...

Utilize Multer to upload images stored within an array of objects

I've been having difficulty figuring out how to extract the images from an array of objects structured like this: import mongoose from "mongoose"; const prodcutSchema = new mongoose.Schema( { title: { type: String, require ...

Next.js' getInitialProps function does not fetch server-side data

I'm currently working through a tutorial on fetching data with Next.js Instead of following the tutorial exactly, I decided to use axios. However, I'm having trouble getting the desired data using getInitialProps. Here is my code: import axios ...

Tips for creating a binding between an HTTP service and a variable in AngularJS that adjusts when the server data is modified

Using an http get request in angular to extract data into an object with the users currently connected to my app requires refreshing the information every time for binding to the scope. To achieve this, I implemented a method to refresh the data from the a ...

The $.Get method does not retain its value within an each() loop

When using the jQuery each() method on a DropDown select, I iterate through an li element. However, my $.get() function takes time to fetch data from the server, so I use a loading image that toggles visibility. The issue is that the each() method does not ...

What are some tips for managing the hover effect using CSS3?

Here's a demonstration of my current setup. When you hover over the black box, a transition occurs and reveals my tooltip. However, I only want the tooltip to appear when hovering over the black box itself. Currently, the transition also triggers if y ...

Promise and Determination failing to produce results

const { GraphQLServer } = require('graphql-yoga'); const mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/test1"); const Todo = mongoose.model('Todo',{ text: String, complete: Boolean }); const ...

Step-by-step guide on permanently updating the text of select options with JavaScript

Here is the code for a select option with different values: <select id="test" onchange="changeContent()"> <option>1</option> <option>2</option> <option>3</option> </select> The javascript function that chan ...

Utilizing jQuery for animating SVG elements with dynamic color changes and scaling effects upon hover

Seeking assistance from coding experts! I have created an icon and am attempting to modify it so that the color changes when hovered over. Additionally, I want the white square to scale down by 50% starting from the top-left corner of its current position. ...

When attempting to navigate to a different page in Next.js, the Cypress visit functionality may not function as

In my upcoming application, there are two main pages: Login and Cars. On the Cars page, users can click on a specific car to view more details about it. The URL format is as follows: /cars for the general cars page and /cars/car-id for the individual car p ...

Struggling with JavaScript conditional statements

Currently, I am in the process of creating a login and registration panel using jQuery and PHP. Essentially, if there are any errors during registration, it sets certain form errors, redirects back to the registration page, the JavaScript identifies these ...

What causes the cursor in an editable div to automatically move to the front of the div?

<div className="min-w-[600px] min-h-[36.8px]" > <div id={`editableDiv-${Object.keys(item)}-${index}`} className="p-3" contentEditable suppressContentEditableWarning onInput={(e) => onChange(e)} > ...

Initiate an AJAX call

Hey there, I have a piece of code that I need some help with. <button onclick="sbt()" name="step1[save]" type="submit" class="btn-type5 next-btn-form pie" value="Далее">Send</button> function sbt(){ var phone = document.getElementById(&ap ...

What is the correct approach to importing the Select class in JavaScript with WebDriver?

I'm having trouble using the Select function in my code to interact with a dropdown menu. I attempted to import Select from the "selenium-webdriver" package, but it doesn't seem to be working. All of the search results I've found on this top ...

Exploring Vue and Webpack: Optimizing global variables for development and production environments

I have been using vue-cli to create my web application. Throughout the app, I am making use of an API by including it in various places like this: axios.post(API + '/sign-up', data).then(res => { // do something }); The API variable is a c ...

Difficulty altering link hover background color

I'm having trouble changing the hover effect background-color on the tweets of this page: Despite my efforts, all the links except for the latest tweets are working perfectly. What am I missing? Here's what I've been trying... <script& ...

Utilize D3's pie chart to showcase the data in JSON's individual collections

I am currently working on creating a pie chart that displays the distribution of collections based on their names. I have come across an issue where d3.layout.pie().value() only evaluates specified array values. Is there a solution available to extract the ...

Adjust a parameter within a MongoDB array entity

I am attempting to update a value within an array of objects. Looking at the MongoDB schema above, my goal is to find an expense with an ID that matches the _id and update the fields with new values from req.body. Specifically, I need to update expensesTyp ...

Progressive Web App (PWA) default start URL

I am currently facing an issue with my Vue app, which is also a Progressive Web App (PWA). While the PWA functions correctly as planned, I realized that I am using generic paths for my web application. This means that in order to access the correct page, ...