The crux of solving this problem is in the fact that, the diagonal cutting a vertical line enters in one unique square, and when it cuts a vertical line enters another unique square.
Case 1: $N/M$ is irreducible
Draw them yourself and be convinced with that fact! And then the total number will emerge by adding $N-1$ vertical lines $=$ $N-1$ unique squares, and $M-1$ horizontal lines = $M-1$ unique squares, but the first square is where we started and it was not counted therefore $(N-1)+(M-1)+1 = N+M-1$ is the usual answer, if $N,M$ has no common factor.
The usual confusing point is how come common factor is related to diagonal don't touch any vertices of any of the inside squares.
This can be understood using the slope, taking $s = N/M$, if this is an irreducible rational number than by taking $M$ steps horizontally, you will meet only the vertex at the very last.
Another meaning of this is the following: Only $s \times M$ can produce a natural number $N$, and no other number less than $N$.
Meeting of a interior vertex of a square is not possible because this would mean there exists a number $K<M$ when multiplied to $s$ produces a natural number. Which is in contradiction with the irreducibility of the given $N/M$. And the geometric meaning is that the slope is changed! Which is again not possible! Slope of a straight line remains the same!
Case 2: $N/M$ is reducible
Then for this case, $s = N/M=n/m$ , which means there are interior vertices which the diagonal cuts. Hence the problem is reduced to a case of smallest irreducible $n\times m$ rectangle. Following the same argument from the slope, as it is the same throughout the diagonal, you will reached the top right vertex of the vertical $n$ square, if you walked $m$ squares to the right! And then apply the same $m+n-1$ and then multiply it by $GCD(N,M)$ to get the actual number of squares cut by the diagonal for the $N\times M$ rectangle.
$$n(Sq.)=GCD(N,M)(m+n-1)$$
The $GCD(N,M)$ is basically a multiplication factor, which you will be able to obtain without the need for the jargon $GCD$. It is just the number of the same small rectangles $n\times m$ arranged diagonally to get how it would have appeared if there was $N\times M$ rectangle.