线段上格点的个数

题目大意:给定平面上的两个格点(整数点)p1(x1,y1),p2(x2,y2) 线段p1p2上,除p1和p2以外一共有多少个格点

限制条件:-10^9<=x1,x1,y1,y1<=10^9

输入:p1(1,11) p2(5,3)

输出:3

思路:这题是用辗转相除法来做的,答案就是gcd(abs(x1-x2),abs(y1-y2))-1,为什么可以这样做呢?  仔细想想,求出最大公约数g,也就是把y分为g个部分组成,x也是g个部分组成,这样的话,

从起点开始,每次横坐标和纵坐标分别增加相应的一部分,一直增到终点,这个过程就是模拟的过程。。。  如果要包括端点的话就是以上+2了。。但是要有个特判,当两个点在同一位置时输出0

看代码

#include<iostream>
#include<string.h>
#include<map>
#include<cstdio>
#include<cstring>
#include<stdio.h>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<set>
#include<queue>
typedef long long ll;
using namespace std;
const ll mod=1e9+7;
const int maxn=1e5+10;
const int maxk=5e3+10;
const int maxx=1e4+10;
const ll maxe=1000+10;
#define INF 0x3f3f3f3f3f3f
#define Lson l,mid,rt<<1
#define Rson mid+1,r,rt<<1|1
int gcd(int a,int b)
{
    return b==0?a:gcd(b,a%b);
}
int main()
{
    int x1,y1,x2,y2;
    cin>>x1>>y1>>x2>>y2;
    if(abs(x1-x2)==0&&abs(y1-y2)==0) cout<<"0"<<endl;
    else
    cout<<gcd(abs(x1-x2),abs(y1-y2))-1<<endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/caijiaming/p/9424837.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值