Finding all the n digit numbers that have sum of even and odd positioned digits divisible by given numbers - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in three numbers. Let's say the three numbers are a, b and n.

Our job is to find all the n-digit numbers whose sum of digits at even positions and odd positions are divisible by a and b respectively. And we have to lastly return an array containing all the required numbers, the array should be empty if there are no matching numbers.

Example

Following is the 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));

Output

This will produce the following output in 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
]
raja
Published on 30-Sep-2020 17:37:12
Advertisements