Files
freeCodeCamp/curriculum/challenges/japanese/22-rosetta-code/rosetta-code-challenges/least-common-multiple.md
2024-01-24 19:52:36 +01:00

2.2 KiB
Raw Blame History

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
5a23c84252665b21eecc7edf 最小公倍数 1 302301 least-common-multiple

--description--

The least common multiple of 12 and 18 is 36, because 12 is a factor (12 × 3 = 36), and 18 is a factor (18 × 2 = 36), and there is no positive integer less than 36 that has both factors. As a special case, if either m or n is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of m, until you find one that is also a multiple of n. If you already have gcd for greatest common divisor, then this formula calculates lcm.

\\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)}

--instructions--

整数の配列の最小公倍数を計算してください。 mn が与えられたとき、最小公倍数は、mn の両方の倍数を持つ最小の正の整数となります。

--hints--

LCM は関数とします。

assert(typeof LCM == 'function');

LCM([2, 4, 8]) は数値を返す必要があります。

assert(typeof LCM([2, 4, 8]) == 'number');

LCM([2, 4, 8])8 を返す必要があります。

assert.equal(LCM([2, 4, 8]), 8);

LCM([4, 8, 12])24 を返す必要があります。

assert.equal(LCM([4, 8, 12]), 24);

LCM([3, 4, 5, 12, 40])120 を返す必要があります。

assert.equal(LCM([3, 4, 5, 12, 40]), 120);

LCM([11, 33, 90])990 を返す必要があります。

assert.equal(LCM([11, 33, 90]), 990);

LCM([-50, 25, -45, -18, 90, 447])67050 を返す必要があります。

assert.equal(LCM([-50, 25, -45, -18, 90, 447]), 67050);

--seed--

--seed-contents--

function LCM(A) {

}

--solutions--

function LCM(A) {
  var n = A.length,
    a = Math.abs(A[0]);
  for (var i = 1; i < n; i++) {
    var b = Math.abs(A[i]),
      c = a;
    while (a && b) {
      a > b ? (a %= b) : (b %= a);
    }
    a = Math.abs(c * A[i]) / (a + b);
  }
  return a;
}