我们需要编写一个JavaScript函数,该函数接受三个数字A,B和N,并求出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(2, 5, 3));
输出结果
以下是控制台中的输出-
[ 30, 35, 60, 65, 90, 95 ]