您的位置:首页 > 其它

快速乘法,幂计算 hdu5666

2016-04-17 23:33 211 查看


在实际应用中为了防止数据爆出,在计算a*b%m和x^n%m时,可以采用此方法。在数论中有以下结论:

a*b%m=((a%m)*(b*m))%m ;

(a+b)%m=(a%m+b%m)%m ;

_int64 Plus(_int64 a, _int64 b,_int64 m) { //计算a*b%m
_int64 res = 0;
while (b > 0) {
if (b & 1)
res=(res+a)%m;
a = (a << 1) % m;
b >>= 1;
}
return res;
}
_int64 Power(_int64 x, _int64 n,_int64 m) { //计算x^n%m
_int64 res=1;
while (n > 0) {
if (n & 1)
res=(res*x)%m;
x = (x*x)%m;
n>>= 1;
}
return res;
}


例题:HDU 5666

Segment

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


[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
First line has a number,T,means testcase number.

Then,each line has two integers q,P.

q is a prime number,and 2≤q≤1018,1≤P≤1018,1≤T≤10.

[align=left]Output[/align]
Output 1 number to each testcase,answer mod P.

[align=left]Sample Input[/align]

1
2 107

[align=left]Sample Output[/align]

0

分析可知。在横坐标为 i 处的直线为 y=(p-i)/i *x,显然gcd(p,i)==1,从而直线上的点只有(0,0)和(i,p-i)为整点。发现了这一点最后不难求出来总的点个数为:
(p-2)+(p-3)+...+1=(p-1)(p-2)/2 。考虑到中间结果溢出的情况,从而可以采用快速乘法模运算。

#include<iostream>
using namespace std;
_int64 Plus(_int64 a, _int64 b, _int64 m);
int main() {
_int64 p,q,T;
cin >> T;
while (T--) {
cin >> q >> p;
cout << Plus((q-1)%2, q-2, p) << endl;
}
return 0;
}
_int64 Plus(_int64 a, _int64 b,_int64 m) {
_int64 res = 0;
while (b > 0) {
if (b & 1)
res = (res + a) % m;
a = (a+a) % m;
b >>= 1;
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: