链接:http://www.lightoj.com/volume_showproblem.php?problem=1077

题意:给出平面上两个点,求这两点连成的线段上的整点个数。数据范围是32位有符号整数。

思路:一开始觉得是几何题,但是用几何的方法来做很明显会T。简单的方法是求出gcd(abs(x2-x1),abs(y2-y1))+1即可。想象一下,一条斜着的线段,要求线段上的整点个数,求出横坐标差与纵坐标差的最大公约数就差不多了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<stdlib.h>
using namespace std;
typedef  long long LL;
LL gcd(LL a,LL b)
{
    if(a<b)
    {
        LL temp;
        temp=a;
        a=b;
        b=temp;
    }
    LL r;
    if(a==0||b==0)
        return a+b;
    r=a%b;
    while(r)
    {
        a=b;
        b=r;
        r=a%b;
    }
    return b;
}
int main()
{
    int t,ca=1;
    double a,b,c,d;//LL也可以
    LL ans,x,y;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
// scanf("%lld%lld%lld%lld",&a,&b,&c,&d);
        x=fabs(c-a),y=fabs(d-b);
        ans=gcd(x,y)+1;
        printf("Case %d: %lld\n",ca++,ans);//%I64d就wa
    }
    return 0;
}

 

 

 posted on 2013-07-19 13:07  ∑求和  阅读(293)  评论(3编辑  收藏  举报