freeCodeCamp/guide/chinese/certifications/coding-interview-prep/project-euler/problem-5-smallest-multiple/index.md

1.1 KiB
Raw Blame History

title localeTitle
Smallest multiple 最小的倍数

问题5最小的倍数

方法:

  • 在这个挑战中我们需要找到1到n个数的LCM。
  • 要查找数字的LCM我们使用以下公式
  • LCM
  • 为了找到两个数的GCD最大公约数我们使用欧几里德算法。
  • 一旦我们得到两个数字的LCM我们就可以得到从1到n的数字的LCM。

解:

//LCM of two numbers 
 function lcm(a, b){ 
  return (a*b)/gcd(a, b); 
 } 
 
 //Euclidean recursive algorithm 
 function gcd(a, b){ 
  if (b === 0) return a; 
  return gcd(b, a%b); 
 } 
 
 function smallestMult(n){ 
  let maxLCM = 1; 
 
  //Getting the LCM in the range 
  for (let i = 2; i <= n; i++){ 
    maxLCM = lcm(maxLCM, i); 
  } 
  return maxLCM; 
 } 

参考文献: