우리는 세 개의 숫자 A, B, N을 받아 짝수 위치의 자릿수와 홀수 위치의 자릿수의 합이 각각 A와 B로 나누어지는 N자리 숫자의 총 개수를 찾는 JavaScript 함수를 작성해야 합니다.
예시
이 함수의 코드를 작성해 봅시다 -
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 ]