If the slope of the line is 0 or there is no slope, there is a $NC (m,3) +MC (n,3) $ scheme. If the slope of the line is not 0, just consider the case where the slope is positive, and the final answer is multiplied by 2. To enumerate the coordinates of two points, set $t=\min (n,m) $, there are:
\[\begin{eqnarray*}
Ans&=&\sum_{i=1}^n\sum_{j=1}^m (n-i) (M-j) (\GCD (I,J)-1) \ \
&=&\SUM_{D=1}^T\SUM_{I=1}^N\SUM_{J=1}^M[\GCD (I,J) =d] (n-i) (M-j) (\GCD (I,J)-1) \ \
&=&\SUM_{D=1}^T\SUM_{I=1}^{\LFLOOR\FRAC{N}{D}\RFLOOR}\SUM_{J=1}^{\LFLOOR\FRAC{M}{D}\RFLOOR}[\GCD (I,J) = 1] (N-di) (M-DJ) (d-1) \ \
&=&\sum_{d=1}^t (d-1) \sum_{i=1}^{\lfloor\frac{n}{d}\rfloor}\sum_{j=1}^{\lfloor\frac{m}{d}\rfloor} (N-di) (M-DJ) \SUM_{K|\GCD (i,j)}\mu (k) \ \
&=&\sum_{d=1}^t (d-1) \sum_{i=1}^{\lfloor\frac{n}{d}\rfloor}\sum_{j=1}^{\lfloor\frac{m}{d}\rfloor} (N-di) (M-DJ) \sum_{k|i,k|j}\mu (k) \ \
&=&\sum_{d=1}^t (d-1) \sum_{k}\mu (k) \sum_{k|i}\sum_{k|j} (N-di) (M-DJ) \ \
&=&\sum_{d=1}^t (d-1) \sum_{k}\mu (k) \sum_{k|i} (N-di) \sum_{k|j} (M-DJ) \ \
&=&\sum_{d=1}^t (d-1) \sum_{k}\mu (k) Cal (N,d,k) Cal (M,d,k)
\end{eqnarray*}\]
which
\[\begin{eqnarray*}
Cal (N,d,k) &=&\sum_{k|i} (N-di) \ \
&=&n\sum_{k|i}1-d\sum_{k|i}i\\
&=&N\LFLOOR\FRAC{N}{DK}\RFLOOR-\FRAC{DK (1+\lfloor\frac{n}{dk}\rfloor) \lfloor\frac{n}{dk}\rfloor}{2}
\end{eqnarray*}\]
Set $d=dk$, there are:
\[\begin{eqnarray*}
F (n,d) =cal (n,d,k) &=&n\lfloor\frac{n}{dk}\rfloor-\frac{dk (1+\lfloor\frac{n}{dk}\rfloor) \lfloor\frac{n}{ dk}\rfloor}{2}\\
&=&n\lfloor\frac{n}{d}\rfloor-\frac{d (1+\lfloor\frac{n}{d}\rfloor) \lfloor\frac{n}{d}\rfloor}{2}\\
Ans&=&\sum_{d=1}^t (d-1) \sum_{k}\mu (k) Cal (N,d,k) cal (m,d,k) \ \
&=&\sum_{k=1}^t\mu (k) \sum_{d} (D-1) cal (N,d,k) cal (m,d,k) \ \
&=&\sum_{k=1}^t\mu (k) \sum_{k| D} (\frac{d}{k}-1) f (n,d) f (m,d) \ \
&=&\sum_{d=1}^t f (n,d) F (m,d) \sum_{k| D}\mu (k) (\frac{d}{k}-1) \ \
&=&\sum_{d=1}^t f (n,d) F (m,d) (\sum_{k| D}\mu (k) \frac{d}{k}-\sum_{k| D}\mu (k)) \ \
&=&\sum_{d=1}^t f (n,d) F (m,d) (\varphi (D)-[d=1])
\end{eqnarray*}\]
To sum up, it is only necessary to find out all Euler functions and calculate the time complexity $o (n) $ in a linear sieve.
#include <cstdio>typedef long long ll;const int n=50010,p=1000000007;int n,m,t,i,j,ans,phi[n],v[n],p[n],tot; Inline ll Cal (ll N,ll D) {return n/d*n-d* (n/d) * (n/d+1)/2;} ll C (ll N) {return n (n-1) * (n-2)/6;} int main () { scanf ("%d%d", &n,&m);t=n<m?n:m; for (phi[1]=1,i=2;i<=t;i++) { if (!v[i]) p[++tot]=i,phi[i]=i-1; for (j=1;j<=tot;j++) { if (i*p[j]>t) break; V[i*p[j]]=1; if (i%p[j]==0) {phi[i*p[j]]=phi[i]*p[j];break;} else phi[i*p[j]]=phi[i]* (p[j]-1); } } for (i=1;i<=t;i++) ans= (ans+cal (n,i)%p*cal (m,i)%p* (phi[i]-(i==1))%P)%P; Return printf ("%d", (Ans*2%p+c (m)%p*n%p+c (n)%p*m%p)%P), 0;}
BZOJ3518: Point Group Count