
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
Sum Which is Divisible by N in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers, arr, as the first argument, and a number, num, as the second argument. Our function should return the number of (contiguous, non-empty) subarrays that have a sum divisible by num.
For example, if the input to the function is −
const arr = [4, 5, 0, -2, -3, 1]; const num = 5;
Then the output should be −
const output = 7;
Output Explanation
There are 7 subarrays with a sum divisible by 5 −
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Example
The code for this will be −
const arr = [4, 5, 0, -2, -3, 1]; const num = 5; const divisibleSum = (arr = [], num = 1) => { const map = {}; let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; const key = ((sum % num) + num) % num; map[key] = map[key]+1||1; }; let s = 0; for (let i = 0; i < num; i++) { if (map[i] > 1) { s += (map[i] * (map[i] - 1)) / 2; } } return s + (map[0]||0); }; console.log(divisibleSum(arr, num));
Output
And the output in the console will be −
7
Advertisements