HDU - 5666 Segment (大数位运算)好题

HDU - 5666
Segment
Time Limit: 1000MS   Memory Limit: 65536KB   64bit IO Format: %I64d & %I64u

Submit Status

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   .The segment intersect the axis and produce a delta.She links some line between    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.  

 is a prime number,and  
 

Output

Output 1 number to each testcase,answer mod P.
 

Sample Input

     
     
     
     
1 2 107
 

Sample Output

     
     
     
     
0
 

Source

BestCoder Round #80
//题意:方程x+y=q;
告诉你q,然你求这条直线在第一象限有多少个整数坐标,在直线上的不算。
//思路:
很容易找出规律[(q-2)*(q-1)/2]%p,但是因为数太大,所以在大数取余时得用一个技巧,就是把其中一个大数化小,再逐个相乘取余。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#define ll __int64
using namespace std;
ll p_mod(ll q1,ll q2,ll p)
{
	ll sum=0;
	while(q2)
	{
		if(q2&1)
		{
			sum+=q1;
			sum%=p;
		}
		q1<<=1;
		q1%=p;
		q2>>=1;
	}
	return sum;
}
int main()
{
	int t,n,m;
	ll p,q;
	ll q1,q2,pp;
	int i,j,k;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%lld%lld",&q,&p);
		q1=q-1;q2=q-2;
		if(q1&1)
			q2>>=1;
		else
			q1>>=1;
		printf("%lld\n",p_mod(q1,q2,p));
	}
	return 0;
}

你可能感兴趣的:(HDU - 5666 Segment (大数位运算)好题)