计算偶数和奇数位置数字之和能被给定数字整除的 N 位数字 - JavaScript

javascriptobject oriented programmingweb developmentfront end technology更新于 2025/11/24 10:52:17

我们需要编写一个 JavaScript 函数,该函数接受三个数字 A、B 和 N,并找出偶数位置和奇数位置数字之和分别能被 A 和 B 整除的 N 位数字的总数。

示例

让我们来编写该函数的代码 −

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 ]

相关文章


有用资源