FCC_Intermediate Algorithm_Smallest Common Multiple

1.任务及要求

Smallest Common Multiple


找出能被两个给定参数和它们之间的连续数字整除的最小公倍数。

范围是两个数字构成的数组,两个数字不一定按数字顺序排序。

例如对 1 和 3 —— 找出能被 1 和 3 和它们之间所有数字整除的最小公倍数。

如果你被卡住了,记得开大招 Read-Search-Ask 。尝试与他人结伴编程、编写你自己的代码。

2.我的解法

 1 // 最大公约数参考:博客园:https://www.cnblogs.com/Kiven5197/p/5656200.html
 2 
 3 function smallestCommons(arr) {
 4   arr.sort(function(a,b){return a-b;});
 5   var result = 1;
 6   for(i = arr[0]; i <= arr[1]; i++){
 7     result =lcm(result,i);
 8   }
 9   return result;
10 }
11 
12 
13 smallestCommons([1,5]);
14 
15 //求两数的最大公约数,欧几里得算法(辗转相除法)
16 function gcd(a,b){
17  
18     var r;  
19     while(b>0)  
20     {  
21          r=a%b;  
22          a=b;  
23          b=r;  
24     }  
25     return a;
26 }
27 
28 //求两数的最大公约数,相减法
29 function gcd2(a,b) {
30   while ( a!=b) {
31     if (a>b){
32       a=a-b; 
33     } else {
34       b=b-a;
35     }
36   }
37     return a;
38 }
39 
40 // 求两数的最小公倍数(两数乘积除以其最大公约数)
41 function lcm(a,b) {
42   return a*b/gcd(a,b); 
43   // return a*b/gcd2(a,b);
44 }

3.发现的其他解法

// CSDN:https://blog.csdn.net/kyr1e/article/details/78717760

// 博客园:https://www.cnblogs.com/lilicat/p/6256025.html

猜你喜欢

转载自www.cnblogs.com/yoursatan/p/12506107.html