TITLE: how can I minimise (n * y) (mod x) for known x and y, and for a given range of n?
QUESTION [10 upvotes]: How can I minimise (n.y) (mod x), for known x and y, and for a given range of n?
($x$ and $y$ are actually the components of a 2D vector for a line for which I'm trying to generate a set of bounding integer points)
So, for example, if x = 61, y = 17, and n must be in the range 0 < n < 12, then minimum value of the modulo operation is at n = 11, i.e. (11 * 17) (mod 61) = 4.
If we changed the range to 0 < n < 9, the minimum value is then at n = 4,  i.e. (4 * 17) (mod 61) = 7.
I need to be able solve this for arbitrary values, but within a known range (around +/- 3000000).
This is a practical question so if there is no direct solution (or if a direct solution is very complicated) then a numerical method may be preferrable.

REPLY [4 votes]: What I'm going to say is somewhat similar to Roland's answer but more precise in the case when the range for $n$ is given in the form of upper bound, i.e., $0 < n < N$. 
Notice that $ny\bmod x = ny - kx$ for some integer $k$. We want to minimize $ny-kx$ that, if we disregard for a moment the sign, can be formulated as minimizing 
$$\left|n\frac{y}{x} - k\right|$$
over integer $n$ in the given range and arbitrary integer $k$.
It is known that if some $n,k$ give better approximation (in the sense of the above absolute value) than any other $n',k'$ with $n' < n$, then $\frac{k}{n}$ with necessity represents a convergent to $\frac{y}{x}$.
Therefore, a first good candidate for the anticipated $n$ is the largest denominator of a convergent $\frac{k}{n}$ for $\frac{y}{x}$ that fits the given range (i.e., $n < N$).
For such $n$, if we have $n\frac{y}{x} - k > 0$ (equivalently, $\frac{k}{n}<\frac{y}{x}$), then it is indeed a solution. 
However, if $n\frac{y}{x} - k < 0$ (equivalently, $\frac{k}{n}>\frac{y}{x}$), then the solution is given by largest allowed denominator of a semi-convergent located between the preceding and subsequent convergents of $\frac{k}{n}$. That is, if $\frac{k'}{n'}, \frac{k}{n}, \frac{k''}{n''}$ are consecutive convergents, then $\frac{k'}{n'} < \frac{k''}{n''} < \frac{y}{x}$ and $n' < N \leq n''$. Then one needs to find a semi-convergent between $\frac{k'}{n'}$ and $\frac{k''}{n''}$ with the largest denominator smaller than $N$.