Chúng ta cần viết hàm nhận vào ba số a, b, n. Tìm tất cả số n chữ số mà tổng chữ số ở vị trí chẵn chia hết cho a, tổng vị trí lẻ chia hết cho b. Trả về mảng các số thỏa mãn, rỗng nếu không có.
Ví dụ
Dưới đây là đoạn code:
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));Kết quả
Đoạn code sẽ in ra console:
[ 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 ]