Locate the product of n numerals within a specified interval

Is there a way to determine the number of multiples for N unique numbers (provided as an array input) within the range of 1 to K, where 1 < K < 10⁸ and 3 ≤ N < 25?

function findNumberOfMultiples(inputArray, maxSize) {   
    var count = 0;
    var tempArray = [];
    for (var i=0; i<maxSize; i++){
        tempArray[i] = 0;
    }

    for (var j=0; j<inputArray.length; j++) {
        for (var i=1; i<=maxSize; i++) {
            if (i % inputArray[j]) {
                tempArray[i-1] = 1;
            }
        }
    }

    for (var i=0; i<maxSize; i++) {
        if (tempArray[i]==1) {
            count++;
        }
    }
 return count;
}

This program may not be efficient when dealing with large values of K. For instance, if you have inputArray = [2,3,4] and the value of maxSize(k) is 5,

  • Multiples of 2: 2, 4
  • Multiples of 3: 3
  • Multiples of 4: 4

Therefore, the total number of multiples of either 2, 3, or 4 in the range of 1 to 5 is 3.

Answer №1

To tackle this problem, you can utilize an algorithm with a time complexity of O(N^2), where N represents the number of elements in your given array.

Imagine having two elements in your array, denoted as [a1,a2], with a specified range of K.

Your resulting formula would be:

  K/a1 + K/a2 - K/lcm(a1,a2) // due to adding them in both a1 and a2

Therefore, if you have a1,...,ax elements, the equation becomes:

K/a1+...K/ax - K/lcm(ai,aj) (substituting i,j with (n*n-1)/2 combinations)

The operation K/lcm(ai,aj) will run O(N^2) times ((n*n-1)/2 times exactly). Hence, the overall complexity is O(N^2) (with a Log(min(ai,aj)) element that doesn't significantly impact the overall performance).

 public int combinations(int K, int[] input){
    int total = 0;
    for(int i=0;i<input.length;i++){
        total  =  total + Math.floor(K/input[i]);
    }
    for(int i=0;i<input.length;i++){
        for(int j=i+1;j<input.length;j++){
            if(i!=j){
                int lcm =lcmFind(input[i], input[j]);
                total = total - Math.floor(K/lcm);
            }
        }
    }
    return total;
}

The specific test case provided:

Answer №2

Here is a useful function that gets the job done:

const countMultiples = (arr, max) => {
  const multiplesArr = [];
  for (let j = 0; j < arr.length; j++) {
    const num = arr[j];
    const limit = max / num;
    for (let i = 1; i < limit; i++) {
      const multiple = i * num;
      if (!multiplesArr.includes(multiple)) {
        multiplesArr.push(multiple);
      }
    }
  }
  return multiplesArr.length;
};

Note: While this function does not cause any stack errors, using large values for the range might lead to browser freezing issues.

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

How can I implement a single-column search feature in a GridView using Javascript in ASP.NET?

I found a Google function for client-side searching in a grid using a textbox Here is the function: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> function searchFunction(phrase, ...

Is there a way for me to detect when the progress bar finishes and execute a different function afterwards?

After clicking a button in my Javascript function, the button disappears and a progress bar is revealed. How do I trigger another function after a certain amount of time has passed? $('#go').click(function() { console.log("moveProgressBar"); ...

Adjust jqGrid dimensions automatically as browser window is resized?

Does anyone know of a method to adjust the size of a jqGrid when the browser window is resized? I attempted the approach mentioned here, but unfortunately, it does not function correctly in IE7. ...

Using THREE.js to animate objects and have them settle onto a specific face

I'm currently working on adding pins to a curved map of the US, but I'm facing some challenges. Right now, I'm using mathematical calculations to determine their distance from the highest part of the curve and adjust their height accordingly ...

Ways to enhance a Vue component using slots

I am looking to enhance a third-party library component by adding an extra element and using it in the same way as before. For example: <third-party foo="bar" john="doe" propsFromOriginalLibrary="prop"> <template v ...

How can we verify that console.log has been called with a specific subset of expected values using Jest?

I am currently experimenting with a function that adds logging and timing functionality to any function passed to it. However, I am facing a challenge when trying to test the timing aspect of it. Here are my functions: //utils.js export const util_sum = ( ...

In the world of Express, the res.write function showcases the magic of HTML elements contained within

Currently diving into web app development, I have ventured into using express and implemented the following code snippet: app.post("/", function(req, res) { var crypto = req.body.crypto; var fiat = req.body.fiat; var amount = req.body.amount; va ...

Utilizing JSON with AJAX to dynamically fetch data on a separate webpage results in the page reloading despite implementing the e.preventDefault() method

Looking to retrieve a value on a new page and navigate without refreshing? I'm utilizing the POST method here along with JSON to fetch values. Still learning the ropes of this Ajax code! My goal is to move from the team.php controller page to team_d ...

Is it possible to hide a menu by removing a class when the user clicks outside the menu?

I've come across a lot of information about how to close a menu when clicking outside of it, but my question is, can the following code be simplified to something like if you don't click on #menu > ul > li > a then removeClass open. Can ...

Is Angular File API Support Compatible with HTML5?

When checking for HTML5 File API browser support in my code: private hasHtml5FileApiSupport; constructor(@Optional() @Inject(DOCUMENT) document: Document) { const w = document.defaultView; this.hasHtml5FileApiSupport = w.File && w.FileReader & ...

How can I efficiently utilize HTML/CSS/JS to float items and create a grid that accommodates expandable items while minimizing wasted space?

After meticulously configuring a basic grid of divs using float, I've encountered an issue. When expanding an item in the right-hand column, the layout shifts awkwardly. My goal is to have boxes A and B seamlessly move up to fill the empty space, whi ...

Load the flexslider once the fancybox container is opened

In my experience, I have found flexslider and fancybox to be very useful plugins. Individually, they work perfectly fine on a website that I am currently working on. However, when I tried placing a flexslider gallery inside a fancybox div, I encountered a ...

What is the best way to adjust the size of an IMG element while ensuring it remains proportionate and in the same position when the window size is altered?

I am currently in the process of developing a GPS-inspired application, and I have encountered a roadblock while attempting to establish 'no-go' zones on the map. My goal is to have the map dynamically resize based on the window dimensions, using ...

Vue's emission system, accessed through this.$emits, unexpectedly ceases functioning mid-function call

Within my Vue frontend, I have a function designed to emit updates to the parent component before and after sending a request to the server. The function in question is as follows: saveUpdates: async function () { const component = { doc: ...

Steps to restrict input in a text area to only backspace and cursor movements

I'm in search of a jQuery function that restricts movements to only arrow keys and backspace within a textarea. However, there seems to be an issue with the arrow key movements not functioning correctly. function moveArrow(e){ if(e.which >= 3 ...

What causes the scrollTop to appear erratic?

There is a simple issue that I find difficult to explain in text, so I have created a video demonstration instead. Please watch the video at this link: The functionality on my page works perfectly when scrolling down, as it replaces images with the next i ...

Error: Trying to send FormData to ajax results in an Illegal Invocation TypeError being thrown

Successfully sending a file to the server for processing using the code below: var formData = new FormData(); formData.append('file', $('#fileUpload')[0].files[0]); options = JSON.stringify(options); // {"key": "value"} $.ajax({ ...

Error in Next.js: The element type is not valid. Please make sure it is either a string (for built-in components) or a class/function (for composite components) and not undefined

I've encountered an issue while working on my Next.js project where I am trying to import the Layout component into my _app.js file. The error message I received is as follows: Error: Element type is invalid: expected a string (for built-in componen ...

Ensuring React's setupProxy functions properly in conjunction with express.js

I've encountered an issue while trying to pass images from express to react. My express.static is correctly set up, so when I visit localhost:5000/public/images/me.jpeg, the image loads in my browser. However, when I attempt to use <img src="/publi ...

Establishing a dynamic database feature (such as a real-time leader board) on a website

Recently, I designed a fun JavaScript game for my website and now I am contemplating adding a leaderboard feature. However, I am unsure about which type of database would be the best fit - MongoDB, SQLite, or something else entirely. I have heard that SQ ...