Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count of N-digit Numbers having Sum of even and odd positioned digits divisible by given numbers - JavaScript
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.
Example
Let’s write the code for this function −
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));
Output
Following is the output in the console −
[ 30, 35, 60, 65, 90, 95 ]
Advertisements