Finding the LCM of a range of numbers

前端 未结 14 732
时光说笑
时光说笑 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:44

    Here is my answer in JavaScript. I first approached this from primes, and developed a nice function of reusable code to find primes and also to find prime factors, but in the end decided that this approach was simpler.

    There's nothing unique in my answer that's not posted above, it's just in Javascript which I did not see specifically.

    //least common multipe of a range of numbers
    function smallestCommons(arr) {
       arr = arr.sort();
       var scm = 1; 
       for (var i = arr[0]; i<=arr[1]; i+=1) { 
            scm =  scd(scm, i); 
        }
      return scm;
    }
    
    
    //smallest common denominator of two numbers (scd)
    function scd (a,b) {
         return a*b/gcd(a,b);
    }
    
    
    //greatest common denominator of two numbers (gcd)
    function gcd(a, b) {
        if (b === 0) {  
            return a;
        } else {
           return gcd(b, a%b);
        }
    }       
    
    smallestCommons([1,20]);
    

提交回复
热议问题