Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

how to find lcm in javascript

function smallestCommons(arr) {
  // Sort the array
  arr = arr.sort(function (a, b) {return a - b}); // numeric comparison;
  var min = arr[0];
  var max = arr[1];

  var numbers = [];
  var count = 0;

  //Here push the range of values into an array
  for (var i = min; i <= max; i++) {
    numbers.push(i);
  }
  //Here freeze a multiple candidate starting from the biggest array value - call it j
  for (var j = max; j <= 1000000; j+=max) {

    //I increase the denominator from min to max
    for (var k = arr[0]; k <= arr[1]; k++) {

      if (j % k === 0) { // every time the modulus is 0 increase a counting 
        count++; // variable
      }
    }

    //If the counting variable equals the lenght of the range, this candidate is the least common value
    if (count === numbers.length) { 
      return j; 
    }
    else{
      count = 0; // set count to 0 in order to test another candidate
    }
  }
}

alert(smallestCommons([1, 5]));
Comment

PREVIOUS NEXT
Code Example
Javascript :: convert json result to datatable c# 
Javascript :: convert iso string to datetime javascript 
Javascript :: convert response to json javascript 
Javascript :: javascript console group 
Javascript :: array chaing in js 
Javascript :: placeholder javascript 
Javascript :: javascript syntax for check null or undefined or empty 
Javascript :: all javascript pattern programs 
Javascript :: on focus jquery 
Javascript :: axios.post request with custom headers 
Javascript :: how do you make a random array in javascript 
Javascript :: 3 = signs in javasdcript 
Javascript :: javascript file drag and drop 
Javascript :: icon refresh material ui 
Javascript :: luxon timestamp 
Javascript :: fetching foreign key data in sequelize 
Javascript :: redux dev tools 
Javascript :: javascript remove property from object 
Javascript :: javascript array delete by index 
Javascript :: import applymiddleware 
Javascript :: on function change body background image 
Javascript :: remove element from array in js 
Javascript :: javascript array flat 
Javascript :: cube root of a number in js 
Javascript :: node red admin password setting 
Javascript :: genius api 
Javascript :: foreach reverse javascript 
Javascript :: update array of object using other array javascript 
Javascript :: js map constructor 
Javascript :: laravel jquery csrf 
ADD CONTENT
Topic
Content
Source link
Name
6+5 =