Gao the Grid zoj3647(数论)

来源:互联网 发布:网站美工 编辑:程序博客网 时间:2024/05/22 22:51

Description

n * m grid as follow:

a n*m grid(n=4,m=3)

Count the number of triangles, three of whose vertice must be grid-points.
Note that the three vertice of the triangle must not be in a line(the right picture is not a triangle).

a triangle not a triangle

Input

The input consists of several cases. Each case consists of two positive integers n and m (1 ≤ nm ≤ 1000).

Output

For each case, output the total number of triangle.

Sample Input

1 12 2

Sample Output

476

hint

hint for 2nd case: C(9, 3) - 8 = 76



思路: 首先的需要知道的一个结论就是 一个向量 (i,j)通过的整数点的个数为gcd(i,j)+1

    证明: 若i,j互质,那么向量(i,j)通过两个整数点

若i,j不互质,那么向量(i,j)=(i’,j‘)*gcd(i,j)  其中(i',j')互质,因此通过的整数点总数为gcd(i,j)+1个,命题得证。

   

   显然,题目的答案为 c((n+1)*(m+1),3)-三点共线的个数。

   若三点共线,则它们位于同一向量上,取向量的两个端点和中间的一个点,考虑上向量的平移,对于向量 (i,j)共有 (n-i+1)*(m-j+1)*(gcd(i,j)-1)对三点共线,

    由对称性可以知道斜率小于0的情况。

代码:

#include <cstdio>#include <cstring>#include <algorithm>#define LL long longconst long M=2100;long n,m;long gcd(long x,long y){while (y){long temp=y;y=x%y; x=temp;}return x;}int main(){while  (~scanf("%d%d",&n,&m)){LL N=1LL*(n+1)*(m+1);LL ans=N*(N-1)*(N-2)/6;;for (long i=0;i<=n;++i)for (long j=0;j<=m;++j)if (i||j){LL now=1LL*(n-i+1)*(m-j+1)*(gcd(i,j)-1);if (i && j) now*=2;ans-=now;}printf("%lld\n",ans);}return 0;}


原创粉丝点击