TITLE: Number of cells intersecting the line segment joining $(0,0)$ and $(m,n)$
QUESTION [5 upvotes]: If $m,n \in \mathbb{N}$ . Let $g(m, n)$ be the number of cells that
   the line joining $(m, n)$ to $(0, 0)$ cuts in the region $0 \le x \le
 m$ and $0 \le y ≤ n$. 
For example $g(1, 1)$ is $1$ because the line joining $(1, 1)$ and
  $(0, 0)$ cuts just one cell. Similarly $g(2, 1)$ is $2$ and $g(3, 2) =
 4$.
Find $g(343, 56)$.

I am trying to derive a formula for any $g(m,n)$. I noticed that for $m=n$ the answer is $m$ but for $m \neq n$ the answer seems be $(m+n-1)$ in general but this does not holds for all. Any ideas how to generalize $m \neq n$ restriction?

REPLY [3 votes]: If ${\rm gcd}(m,n) = d \neq 1$, then you can say that $g(m,n) = d \cdot g(\frac{m}{d},\frac{n}{d})$ as the line can be divided in $d$ parts, each starting at $(0,0)$ and ending at $(\frac{m}{d},\frac{n}{d})$. If however ${\rm gcd}(m,n) = 1$ then you are essentially walking in a rectangle of $m \times n$, starting at the bottom left, ending at the top right corner, and only moving up or right. This takes exactly $m + n - 1$ squares. So if $d = {\rm gcd}(m,n)$ then 
$$g(m,n) = d \cdot \left(\frac{m}{d} + \frac{n}{d} - 1\right) = m + n - d$$
In particular, ${\rm gcd}(343,56) = 7$, so $g(m,n) = 343 + 56 - 7 = 392$.

REPLY [2 votes]: Let $r = {\rm gcd}(m,n)$. The line segment from $(0,0)$ to $(m,n)$ cuts $m-1$ vertical lattice lines and $n-1$ horizontal ones (not including those at the endpoints), but has 
$r-1$ intersections of horizontal and vertical lines, so $g(m,n) = (m-1) + (n-1) - (r-1) + 1 = m + n - r$.