hdu 5666 Segment(快速积)

Segment

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


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
 
  
1 2 107
 

Sample Output
 
  
0
 

题意:给你一个值q,x+y=q为一次函数,它与坐标轴围成一个三角形,问三角形内部有多少个点,结果对p取余。

虽然结果不难看出为(q-1)*(q-2)/2,由于范围太大,直接求会超过long long的范围,像快速幂的求法那样也可以求乘法。

#include<cstdio>
#include <algorithm>  
#include <cstring> 
#define LL long long
using namespace std;
LL GCD(LL n,LL mod)
{
	LL m=n-1,ans;
	n=n-2;
	if(n%2==0)
		n/=2;
	else
		m/=2;
	ans=0;
	while(m)
	{
		if(m&1)
		   ans=(ans+n)%mod;//加法
		m/=2;
		n=(n*2)%mod;
	}
	return ans;	
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		LL q,p,a;
		scanf("%lld%lld",&q,&p);
		a=GCD(q,p);
		printf("%lld\n",a);
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_35634181/article/details/62060017