Count of N-digit Numbers having Sum of even and odd positioned digits divisible by given numbers - JavaScript

JavascriptObject Oriented ProgrammingWeb DevelopmentFront End Technology

<p>We are required to write a JavaScript function that takes in three numbers A, B and N, and finds the total number of N-digit numbers whose sum of digits at even positions and odd positions are divisible by A and B respectively.</p><h2>Example</h2><p>Let&rsquo;s write the code for this function &minus;</p><!---<p><a href="" target="_blank" rel="nofollow" class="demo"><i class="fa-external-link"></i> Live Demo</a></p>---><pre class="prettyprint notranslate">const indexSum = (num, sumOdd = 0, sumEven = 0, index = 0) =&gt; { &nbsp; &nbsp;if(num){ &nbsp; &nbsp; &nbsp; &nbsp;if(index % 2 === 0){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sumEven += num % 10; &nbsp; &nbsp; &nbsp; &nbsp;}else{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sumOdd += num % 10; &nbsp; &nbsp; &nbsp; &nbsp;}; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return indexSum(Math.floor(num / 10), sumOdd, sumEven, ++index); &nbsp; &nbsp;}; &nbsp; &nbsp;return {sumOdd, sumEven}; &nbsp; }; const divides = (b, a) =&gt; a % b === 0; const countNum = (n, first, second) =&gt; { &nbsp; &nbsp;let start = Math.pow(10, (n-1)); &nbsp; &nbsp;const end = Math.pow(10, n)-1; &nbsp; &nbsp;const res = []; &nbsp; &nbsp;while(start &lt;= end){ &nbsp; &nbsp; &nbsp; &nbsp;const { sumEven, sumOdd } = indexSum(start); &nbsp; &nbsp; &nbsp; &nbsp;const condition = divides(first, sumEven) &amp;&amp; divides(second, sumOdd); &nbsp; &nbsp; &nbsp; &nbsp;if(condition){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;res.push(start); &nbsp; &nbsp; &nbsp; &nbsp;}; &nbsp; &nbsp; &nbsp; &nbsp;start++; &nbsp; &nbsp;}; &nbsp; &nbsp;return res; }; console.log(countNum(2, 5, 3));</pre><h2>Output</h2><p>Following is the output in the console &minus;</p><pre class="result notranslate">[ 30, 35, 60, 65, 90, 95 ] </pre>
Updated on 14-Sep-2020 12:58:39