hdoj 5666 Segment(二进制优化乘法, gcd)

来源:互联网 发布:淘宝二手苹果能买吗 编辑:程序博客网 时间:2024/05/21 14:46

Segment

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1555    Accepted Submission(s): 576


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=q.The segment intersect the axis and produce a delta.She links some line between (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 is a prime number,and 2q1018,1P1018,1T10.
 

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

Sample Input
12 107
 

Sample Output
0
 

Source
BestCoder Round #80


两个点之间的整数点数量(不包括端点)有一个公式,若两不相等的点为(x1, y1), (x2, y2),则该两点之间的整数点数为gcd(|x1-x2|, |y1-y2|)-1。

注意到三角形是一个等腰直角三角形并且三角形在第一象限,所以假设直线x+y=q
上面的一个点,C(x,q-x);那么从原点连到这个点上的整数点的个数即为gcd(x,q-x),因为q是质数,设gcd(x,q)=c,那么存在两个互质的数m,n使得m*c=x,n*c=q,那么q-x=(m-n)*c,因为m,n互质,没有任何一个大于一的整数能同时整除这两个数,所以(m-n)跟m还是互质,所以gcd(q-x,x)=gcd(x,q);又因为q是质数,且x<=q,所以gcd(x,q-x)=gcd(x,q)=1,即连线上不会经过三角形内部的点,所以答案就是三角形内部的点的个数。三角形内部+边上的整点是(q+1)+ q + (q-1)...+1 = (q+2)*(q+1)/2, 三角形边上
的点数为3*q,所以三角形内部的点数为(q-1)* (q-2) / 2.

因为q,p都是<=1e18, 所以不能直接相乘再取模。
方法一直接通过java的大数类。
方法二可以模仿快速幂,进行二进制优化。

方法一代码:
import java.math.BigInteger;import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int t = sc.nextInt();while(t-- > 0){BigInteger q, qq, p;BigInteger sub1 = BigInteger.valueOf(-1);BigInteger val = BigInteger.valueOf(2);q = sc.nextBigInteger();p = sc.nextBigInteger();q = q.add(sub1).multiply(q.add(val.negate())).divide(val).mod(p);System.out.println(q);}}}


方法二代码:
#include<iostream>#include<cstdio>using namespace std;int main(void){    long long t, p, q, a, b, ans;    cin >> t;    while(t--)    {        ans = 0;        scanf("%lld %lld", &q, &p);        a = q-1;        b = q-2;        if(a % 2) b /= 2;        else a /= 2;        while(b)        {            if(b%2) ans = (ans+a)%p;            b /= 2;            a = (a+a)%p;        }        printf("%lld\n", ans);    }    return 0;}



0 0