As a part of a programming problem I was solving, we were required to find the first offset of a range at which the number is a odd multiple of another number. For e.g: Take the range $100$ to $120$. Only the odd multiples here are taken for the offsets - so offset 0 corresponds to 101, 1 to 103 and k to $100+2*k+1$ in general. Say we need to find the first odd multiple of 3 in this range - that would be 105. This corresponds to an offset of 2. So, I need to compute a function which can output these offsets, given the initial/ final number ($100/120$ here) in the range and the dividing number (3 in this case).
I found a solution here which says the function should be $(-1/2 × (L + 1 + Pk))\mod Pk$ , where L:start of range, Pk: dividing number (3 in our e.g). I'm unable to understand how this function is the right answer. Could some one please shed some light here?
Note: The above function is explained to some extent by the author here, in the comments - but I still don't get it.
it says $$Q_k = (-1/2x(L+1+P_k)) mod P_k$$ let take case of 100 to 120 and $P_k$ = 3
then, L = 100 => L+1+$P_k$ = 100+1+3 = 104, => -1/2*104 = -52
now, a = b mod n means, a-b is a multiple of n
that means, $Q_k$ + 52 is a multiple of 3.
remainder(52/3) = 1
=>1+2 = 3
=>$Q_k$ = 2
least number greater than or equal to 52, which is divisible by 3 is 54.
54-52 = 2 => $Q_k$ = 2