- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

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;

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]

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));

And the output in the console will be −

7

- Related Questions & Answers
- Find permutation of n which is divisible by 3 but not divisible by 6 in C++
- Find N digits number which is divisible by D in C++
- Sum of first N natural numbers which are divisible by X or Y
- Sum of first N natural numbers which are divisible by 2 and 7 in C++
- Generating a random number that is divisible by n in JavaScript
- Smallest number that is divisible by first n numbers in JavaScript
- Check if product of first N natural numbers is divisible by their sum in Python
- Greatest number divisible by n within a bound in JavaScript
- Maximize the number of sum pairs which are divisible by K in C++
- Find elements of an array which are divisible by N using STL in C++
- Greatest Sum Divisible by Three in C++
- Number of pairs from the first N natural numbers whose sum is divisible by K in C++
- Rearrangement of a number which is also divisible by it in C++
- Count numbers in range 1 to N which are divisible by X but not by Y in C++
- Print all the combinations of N elements by changing sign such that their sum is divisible by M in C++

Advertisements