Find b that (a+b) divisible to K

Question:

I have integer input: 0 < a, K, N < 10^9
I need to find all b numbers that satisfy:

  • a + b <= N
  • (a + b) % K = 0

For example: 10 6 40 -> [2, 8, 14, 20, 26]

I tried a simple brute force and failed (Time Limit Exceeded). Can anyone suggest answer? Thanks

a, K, N = [int(x) for x in input().split()]
count = 0
b = 1

while (a + b <= N):
    if ((a + b) % K) == 0:
        count+=1
        print(b, end=" ")
    b+=1

if (count == 0):
    print(-1)
Asked By: noob_beginner

||

Answers:

To find the list of bs, you can use some maths. First, we note that (a + b) % K is equivalent to a % K + b % K. Also when n % K is 0, that means that n is a multiple of K. So the smallest value of b is n * K - a for the smallest value of n where this calculation is still positive. Once you find that value, you can simply add K repeatedly to find all other values of b.

Answered By: Code-Apprentice

The first condition is trivial in the sense that it just poses an upper limit on b. The second condition can be rephrased using the definition of % as

a + b = P * K

For some arbitrary integer P. From this, is simple to compute the smallest b by finding the smallest P that gives you a positive result for P * K - a. In other words

P * K - a >= 0
P * K >= a
P >= a / K
P = ceil(a / K)

So you have

b0 = ceil(a / K) * K - a
b = range(b0, N + 1, K)

range is a generator, so it won’t compute the values up front. You can force that by doing list(b).

At the same time, if you only need the count of elements, range objects will do the math on the limits and step size for you conveniently, all without computing the actual values, so you can just do len(b).

Answered By: Mad Physicist
b = k - a%k

Example: a=19, k=11, b = 11-19%11 = 11-8 =3

Answered By: Colim
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.