Divisible Sum Pairs

Sort by

recency

|

208 Discussions

|

  • + 0 comments

    javascript

    function divisibleSumPairs(n, k, ar) {
        let totalPairs = 0;
        for (let iteration = 0; iteration < n; iteration++) {
            ar.forEach((element, index) => {
            if (index <= iteration) return;
            if ((ar[iteration] + element) % k === 0) totalPairs++;
            });
        }
        console.info(totalPairs)
        return totalPairs;
    
    }
    
  • + 0 comments

    Typescript solution: I have made the algorithm to run o(n) operation using the hash map, and much better compared to o(n^2) if we use brut force method such as nested for loop.

    function divisibleSumPairs(n: number, k: number, ar: number[]): number {
      // Write your code here
      const freq: { [key: number]: number } = {};
      let count = 0;
      ar.forEach((int) => {
        const remainder = int % k;
        const complement = (k - remainder) % k;
        if (complement in freq) {
          count += freq[complement];
        }
        if (remainder in freq) {
          freq[remainder]++;
        } else {
          freq[remainder] = 1;
        }
      });
      return count;
    }
    
  • + 0 comments

    C++:

    int divisibleSumPairs(int n, int k, vector<int> ar) {
        int count = 0;
        
        for (int i = 0; i < n; ++i)
        {
            for(int j = i; j < n; ++j)
            {   
                if(j != i)
                {
                    if(IsDivisiblyByK(ar[i] + ar[j], k))
                    {
                        count++;
                    }
                }
            }
        }
        return count;
    }
    
  • + 0 comments
    function divisibleSumPairs(n, k, ar) {
        
        let sum=0,count=0,i,j;
        
        for(i=0; i<n; i++){
            for(j=i+1; j<n; j++){
                sum=ar[i]+ar[j];
                if(sum%k==0){
                    count++;
                }
            }
        }
     return count;
    }
    
  • + 0 comments

    I belive so far this is the most simple to understand PYTHON solution without the use of any fancy functions but just if else and loops.

    sets=[]
    
    for i in range(len(ar)):
        for j in range(len(ar)):
            if i<j:
                if (ar[i]+ar[j])%k==0:
                    sets.append((ar[i],ar[j]))
    return len(sets)