快速乘法,幂计算 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; }
相关文章推荐
- UVALive 6838 Flipping Parentheses(线段树、单点更新、区间查询)
- 关于运算符重载
- idea配置
- MATLAB 图片浏览(简易版)
- vc中ShellExecute的使用方法 ShellExecute 执行BAT命令
- C++继承
- 使用emacs进行时间管理(1)——org-mode基本操作
- ubuntu 上连接服务器
- Mysql性能优化三(分表、增量备份、还原)
- 20145316《Java程序设计》第七周学习总结
- 20145303 实验二 Java面向对象程序设计
- RSA算法详解及C语言实现
- Could not find action or result
- Spark框架简介
- 这些日子,2年ABAP经验,开发功能重点序列
- 《网络攻防技术与实践》第七周学习总结
- 机电传动控制第八周作业
- PHP之namespace
- 第3章 相互依存性与贸易的好处
- 1002-Strange fuction