fzu 1752 A^B mod C(快速乘+快速幂取模)
2015-08-03 16:43
411 查看
题目:http://acm.fzu.edu.cn/problem.php?pid=1752
Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,B,C<2^63).
There are multiply testcases. Each testcase, there is one line contains three integers A, B and C, separated by a single space.
For each testcase, output an integer, denotes the result of A^B mod C.
3 2 42 10 1000
124
分析:
这题时间要求高,所以multi_mod和quick_mod一起使用,同时,不要使用%运算,那样很耗时间。
Problem Description
Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,B,C<2^63).
Input
There are multiply testcases. Each testcase, there is one line contains three integers A, B and C, separated by a single space.
Output
For each testcase, output an integer, denotes the result of A^B mod C.
Sample Input
3 2 42 10 1000
Sample Output
124分析:
这题时间要求高,所以multi_mod和quick_mod一起使用,同时,不要使用%运算,那样很耗时间。
#include <iostream> #include<cstdio> using namespace std; typedef long long LL; LL multi_mod(LL a,LL b,LL c){ LL ans=0; while(b){ if(b&1)ans=ans+a; if(ans>=c)ans-=c; a=a+a; if(a>=c)a-=c; b>>=1; } return ans; } int main() { //freopen("cin.txt","r",stdin); LL a,b,c; while(~scanf("%I64d%I64d%I64d",&a,&b,&c)){ LL ans=1; a=a%c; while(b){ if(b&1)ans=multi_mod(ans,a,c); a=multi_mod(a,a,c); b>>=1; } printf("%I64d\n",ans); } return 0; }
相关文章推荐
- Git 02 mac下配置自动提示
- php函数——『解析 xml数据』
- win10正式版官方原版完整镜像下载地址汇总
- uva1660 最大流
- git常用命令
- dp第一步!!!!最长公共子序列 POJ 1458
- codevs1285 宠物收养所 splayTree
- [.Net码农]FileUpload.PostedFile 属性
- JavaBean
- 单链表的逆置--普通循环方法(详细图解)
- Tarjan算法求解无向连通图的割点、割边、点双连通分量和边双连通分量的模板
- IOS下用Zbar实现摄像头扫描二维码和扫描本地相册二维码
- Algorithms—240.Search a 2D Matrix II
- 关于指针的*和&
- 微软账号怎么注册?微软账号注册方法
- 依赖注入与JSR-330的参考实现——Guice
- 分割平面,平面分割空间问题
- CRectTracker源码学习笔记
- VS2012编译Lua5.3.1
- jsp页面中form表单提交到数据库的方法