← back to the blog


smallest multiple shortest solution JavaScript

Posted on October 2nd, 2019 in JavaScript by George

Short version:

function sM(v,p) {
const g=(a,b)=>b===0||a===0?a+b:g(b,a%b),l=(a,b)=>a*b/g(a,b);
let m=p?v:1,x=p?p:v,c=m;
while(m<x)c=l(c,++m);
return c;
}

// provide one or two numbers(subsequent)
sM(23);
sM(18,23);

Long version:

function smallestMult(num1,num2) {
  const gcd = (a, b)=>b===0||a===0?a+b:gcd(b, a % b),lcm=(a,b)=>a*b/gcd(a,b);
  let min=num2?num1:1,max=num2?num2:num1,currentLCM=min;
  while(min<max){currentLCM=lcm(currentLCM, ++min);}
  return currentLCM;
}

// provide one or two numbers(subsequent)
smallestMult(23);
smallestMult(18,23);