LightOJ 1077 How Many Points?

本文介绍了一个简单的算法问题:计算二维平面上两点间(包括端点)的整数点数量。通过示例说明了如何使用最大公约数来解决此问题,并提供了一段C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

Given two pointsAandBon theX-Yplane, output the number of the lattice points on the segmentAB. Note thatAandBare also lattice point. Those who are confused with the definition of lattice point, lattice points are those points which have bothxandyco-ordinate as integer.

For example, forA (3, 3)andB (-1, -1)the output is5. The points are:(-1, -1), (0, 0), (1, 1), (2, 2) and (3, 3).

Input

Input starts with an integerT (≤ 125), denoting the number of test cases.

Each case contains four integers,Ax, Ay, BxandBy. Each of them will be fit into a32bit signed integer.

Output

For each test case, print the case number and the number of lattice points betweenAB.

Sample Input

2

3 3 -1 -1

0 0 5 2

Sample Output

Case 1: 5

Case 2: 2

题目很简单,就是让你求两个整数点连成的线段上的整数点(包括两端)有多少个

比如(1,1)(3,3)之间的点有(1,1),(2,2),(3,3)三个点;

看到这个题我想用斜率来做,结果做了两个小时还是不对,后来才知道思路不对,求下公约数就能出来;


#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int main()
{
    int tCase,t=1;
    long long x1,y1,y2,x2;
    scanf("%d",&tCase);
    while(tCase--)
    {
        scanf("%lld%lld%lld%lld",&x1,&y1,&x2,&y2);
        printf("Case %d: %lld\n",t++,(long long)__gcd(abs(y2-y1),abs(x2-x1))+1);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值