Finding the LCM of a range of numbers

前端 未结 14 929
时光说笑
时光说笑 2020-12-08 05:03

I read an interesting DailyWTF post today, \"Out of All The Possible Answers...\" and it interested me enough to dig up the original forum post where it was submitted. This

14条回答
  •  生来不讨喜
    2020-12-08 05:36

    Here's my javascript solution, I hope you find it easy to follow:

    function smallestCommons(arr) {
      var min = Math.min(arr[0], arr[1]);
      var max = Math.max(arr[0], arr[1]);
    
      var smallestCommon = min * max;
    
      var doneCalc = 0;
    
      while (doneCalc === 0) {
        for (var i = min; i <= max; i++) {
          if (smallestCommon % i !== 0) {
            smallestCommon += max;
            doneCalc = 0;
            break;
          }
          else {
            doneCalc = 1;
          }
        }
      }
    
      return smallestCommon;
    }
    

提交回复
热议问题