Whether the sum of two numbers is divisible by k depends only on their residues modulo k .
So, if k is small enough, you can just count how many numbers each possible remainder has and calculate the number of pairs from that. Assuming k > 0 and all non-negative integers
unsigned long long combinations(unsigned k, unsigned long long *arr, unsigned n) { unsigned long long counts[k] = {0}; unsigned i; for(i = 0; i < n; ++i) { ++counts[arr[i]%k]; }
performs the task in steps O(n+k) . If n small and k very large, the naive algorithm is better.
source share