HDU - Segment

来源:互联网 发布:人工智能程序设计java 编辑:程序博客网 时间:2024/06/04 23:35

Problem Description

    \ \ \ \     Silen August does not like to talk with others.She like to find some interesting problems.

    \ \ \ \     Today she finds an interesting problem.She finds a segment x+y=qx+y=qx+y=q.The segment intersect the axis and produce a delta.She links some line between (0,0)(0,0)(0,0) and the node on the segment whose coordinate are integers.

    \ \ \ \     Please calculate how many nodes are in the delta and not on the segments,output answer mod P.

Input

    \ \ \ \     First line has a number,T,means testcase number.

    \ \ \ \     Then,each line has two integers q,P.

    q\ \ \ \ q    q is a prime number,and 2≤q≤1018,1≤P≤1018,1≤T≤10.2 \le q\le 10^{18},1 \le P \le 10^{18},1 \le T \le 10.2q1018,1P1018,1T10.

Output

    \ \ \ \     Output 1 number to each testcase,answer mod P.

Sample Input
12 107
Sample Output
0


汉语:

问题描述
    \ \ \ \     Rivendell非常神,喜欢研究奇怪的问题.    \ \ \ \     今天他发现了一个有趣的问题.找到一条线段x+y=qx+y=qx+y=q,令它和坐标轴在第一象限围成了一个三角形,然后画线连接了坐标原点和线段上坐标为整数的格点.    \ \ \ \     请你找一找有多少点在三角形的内部且不是线段上的点,并将这个个数对PPP取模后告诉他.
输入描述
    \ \ \ \     第一行一个数T,为测试数据组数.    \ \ \ \     接下来每一行两个数qqq,PPP,意义如题目中所示.    q\ \ \ \ q    q是质数且q≤1018,1≤P≤1018,1≤T≤10q\le 10^{18},1\le P\le 10^{18},1\le T \le 10q1018,1P1018,1T10.
输出描述
    \ \ \ \     对每组数据,输出点的个数模PPP后的值.
输入样例
12 107
输出样例
0

考虑一条以(0,0)(0,0)(0,0)为起点,(x,y)(x,y)(x,y)为终点的线段上格点的个数(不包含端点时),一定是gcd(x,y)−1gcd(x,y)-1gcd(x,y)1,这个很显然吧.

然后整个网格图范围内的格点数目是q∗(q−1)2\frac {q*(q-1)} 22q(q1).

所以答案就是q∗(q−1)2−\frac {q*(q-1)} 2 -2q(q1) 所有线段上的格点的个数.

因为gcd(a,b)=gcd(a,b−a) (b>a)gcd(a,b)=gcd(a,b-a)\ (b>a)gcd(a,b)=gcd(a,ba) (b>a),所以gcd(x,y)=gcd(x,p−x)=gcd(x,p)gcd(x,y)=gcd(x,p-x)=gcd(x,p)gcd(x,y)=gcd(x,px)=gcd(x,p),p是质数,所以gcd(x,y)=1gcd(x,y)=1gcd(x,y)=1,所以线段上都没有格点,所以答案就是q∗(q−1)2\frac {q*(q-1)} 2.


简单的一个数学题目,但是要考虑数据大小的问题,使用快速幂求乘积。

因为要去掉端点,但实际上是 [(q-1)*(q-2)] / 2


#include <cstdio>using namespace std;long long multiply(long long a, long long b, long long p){                               //快速幂求乘积    long long sum = 0;    while (b != 0)    {        if (b % 2 == 1)     //if (b & 1 == 1) 用位操作会更快一点,下同        {            sum += a;            sum %= p;        }        a *= 2;        a %= p;        b /= 2;     //b >>= 1    }    return sum;}int main(){    int T;    long long q, p;    scanf("%d", &T);    while (T--)    {        scanf("%I64d %I64d", &q, &p);        printf("%I64d\n", multiply(q - 1, q - 2, 2*p) / 2);    }    return 0;}


0 0
原创粉丝点击