Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the number of pairs whose sum is divisible by k?

Given a value of k. Such that k<=100000 We have to print the number of pairs such that sum of elements of each pair is divisible by k. under the following condition first element should be smaller than second, and both element should be less than 109.

like image 270
Ashesh Vidyut Avatar asked Oct 21 '22 01:10

Ashesh Vidyut


1 Answers

I've found a solution, let a and b numbers such that (a+b)%k=0 then we have to find that pairs (a,b), where a<b, so let's count how many pairs (a,b) satisfy the condition that a+b=k, for example if k=3 0+3=3, 1+2=3, 2+1=3, 3+0=3 there are 4 pairs but only 2 pairs which is (K+1)/2 (integer division) so similar for find the pairs (a,b) which sum is 2k, 3k,.. nk, and the solution will be (k+1)/2 + (2k+1)/2 + (3k+1)/2 + ... + (nk+1)/2, and that is equal to (k*n*(n+1)/2 + n)/2 with time complexity O(1), take care in the case if n*k=2*10^9, because a can't be more than 10^9 for the given constraint.

like image 60
Kevin Bello Avatar answered Oct 31 '22 09:10

Kevin Bello