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 −

 Live Demo

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

Updated on: 09-Apr-2021

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements