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

หาตัวเลข n หลักที่ผลรวมหลักคู่คี่หารลงตัว - JavaScript

เราต้องเขียนฟังก์ชันที่รับ 3 ตัวเลข a, b, n หาตัวเลข n หลักทั้งหมดที่ผลรวมหลักตำแหน่งคู่และคี่ หารด้วย a และ b ลงตัวตามลำดับ คืนค่าอาร์เรย์ของตัวเลขที่ตรงเงื่อนไข

ตัวอย่าง

โค้ดต่อไปนี้เป็นตัวอย่าง:

const indexSum = (num, sumOdd = 0, sumEven = 0, index = 0) => {
  if(num){
    if(index % 2 === 0){
      sumEven += num % 10;
    }else{
      sumOdd += num % 10;
    };
    return indexSum(Math.floor(num / 10), sumOdd, sumEven, ++index);
  };
  return {sumOdd, sumEven};
};

const divides = (b, a) => a % b === 0;

const countNum = (n, first, second) => {
  let start = Math.pow(10, (n-1));
  const end = Math.pow(10, n)-1;
  const res = [];
  while(start <= end){
    const { sumEven, sumOdd } = indexSum(start);
    const condition = divides(first, sumEven) && divides(second,sumOdd);
    if(condition){
      res.push(start);
    };
    start++;
  };
  return res;
};

console.log(countNum(3, 5, 3));

ผลลัพธ์

จะแสดงผลในคอนโซลดังนี้:

[
  104, 109, 134, 139, 164, 169, 194, 199, 203,
  208, 233, 238, 263, 268, 293, 298, 302, 307,
  332, 337, 362, 367, 392, 397, 401, 406, 431,
  436, 461, 466, 491, 496, 500, 505, 530, 535,
  560, 565, 590, 595, 604, 609, 634, 639, 664,
  669, 694, 699, 703, 708, 733, 738, 763, 768,
  793, 798, 802, 807, 832, 837, 862, 867, 892,
  897, 901, 906, 931, 936, 961, 966, 991, 996
]