Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

คำนวณค่าต่ำสุดร่วมของช่วงตัวเลขด้วย JavaScript

เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ของตัวเลขสองตัว a และ b (a >= b) และคืนค่าต่ำสุดร่วม (LCM) ของตัวเลขทั้งหมดในช่วง [a, b]

แนวทาง

เราจะเขียนฟังก์ชันพื้นฐานที่คำนวณ LCM ของตัวเลขสองตัวก่อน เมื่อได้แล้ว เราจะเรียกใช้แบบรีคอร์ซีฟกับตัวเลขที่อยู่ในช่วง [a, b] และคืนค่าผลลัพธ์สุดท้าย

ตัวอย่างโค้ด

const lcm = (a, b) => {
  let min = Math.min(a, b);
  while (min >= 2) {
    if (a % min === 0 && b % min === 0) {
      return (a * b) / min;
    }
    min--;
  }
  return (a * b);
};

const leastCommonMultipleInRange = (arr, len = arr[0], res = 1) => {
  if (len <= arr[1]) {
    return leastCommonMultipleInRange(arr, len + 1, lcm(res, len));
  }
  return res;
};

console.log(leastCommonMultipleInRange([6, 8]));
console.log(leastCommonMultipleInRange([6, 18]));
console.log(leastCommonMultipleInRange([1, 8]));
console.log(leastCommonMultipleInRange([10, 25]));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้:

168 12252240 840 26771144400