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

นับจำนวน N-digit Numbers ที่ผลรวมตำแหน่งคู่/คี่ หารลงตัวใน JavaScript

โจทย์

หาจำนวน N-digit numbers ที่ผลรวมหลักตำแหน่งคู่หาร 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(2, 5, 3));

ผลลัพธ์

[ 30, 35, 60, 65, 90, 95 ]

คำอธิบาย

indexSum recursive function คำนวณผลรวมหลักตำแหน่งคู่/คี่ (index 0 = หลักหน่วย = odd position)
countNum วนลูปทุก N-digit numbers (10^(n-1) ถึง 10^n-1) ตรวจสอบเงื่อนไข
ตัวอย่าง: 2-digit numbers ที่ sum even หาร 5 ลงตัว และ sum odd หาร 3 ลงตัว ได้ [30,35,60,65,90,95]