Wednesday, 11 September 2013

Finding pairs that sum to a multiple of k

Finding pairs that sum to a multiple of k

Suppose, I have a set of N(N<=10^10) natural numbers. Out of these, I want
to form sets of 2 numbers such that their sum is divisible by k. Suppose,
that N=4,ie, Numbers: 1, 2, 3, 4 and k=2. Hence, the formed sets would
be:: (1,3) and (2,4).
No repetitions and the first element of the set should be less than the
second element.
Following is my code and logic. But I don't know why it is giving
incorrect answers for lage values of N.:
int c[] = new int[K];
for (long j=1;j<=N;j++) {
++c[(int)j%K];//storing remainder in array
}
long count = 0;
if (K%2==0)
count = (c[0]*(c[0]-1) + c[K/2]*(c[K/2]-1))/2;
else
count = c[0]*(c[0]-1)/2;
for (int j=1;j<(K+1)/2;j++) {
count+=c[j]*c[K-j];
}

No comments:

Post a Comment