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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With