挑战程序竞赛系列(15):2.6快速幂运算
来源:互联网 发布:百度人工智能世界第一 编辑:程序博客网 时间:2024/06/01 09:15
挑战程序竞赛系列(15):2.6快速幂运算
详细代码可以fork下Github上leetcode项目,不定期更新。
练习题如下:
- POJ 3641: Pseudoprime numbers
- POJ 1995: Raising Modulo Numbers
POJ 3641: Pseudoprime numbers
判断在当前基数a时,满足费马小定理的伪素数。
代码如下:
public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); while (true) { int p = in.nextInt(); int a = in.nextInt(); if (p == 0 && a == 0) break; if (a != quickPow(a, p, p)){ System.out.println("no"); continue; } if (isPrime(p)) System.out.println("no"); else System.out.println("yes"); } } public static boolean isPrime(int num){ for (int i = 2; i * i <= num; ++i){ if (num % i == 0) return false; } return true; } public static long quickMul(long a, long b, long mod) { long ans = 0; while (b != 0) { if ((b & 1) != 0) { ans = (ans + a) % mod; } b >>= 1; a = (a + a) % mod; } return ans; } public static long quickPow(long a, long b, long mod) { long ans = 1; while (b != 0) { if ((b & 1) != 0) { ans = quickMul(ans, a, mod); } b >>= 1; a = quickMul(a, a, mod); } return ans; }
POJ 1995: Raising Modulo Numbers
取模运算,水题。
代码如下:
public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); int Z = in.nextInt(); while ((Z--) != 0){ int M = in.nextInt(); int N = in.nextInt(); long ans = 0; for (int i = 0; i < N; ++i){ long a = in.nextLong(); long b = in.nextLong(); ans = (ans + quickPow(a, b, M)) % M; } System.out.println(ans); } } public static long quickMul(long a, long b, long mod){ long res = 0; while (b != 0){ if ((b & 1) != 0){ res = (res + a) % mod; } b >>= 1; a = (a + a) % mod; } return res; } public static long quickPow(long a, long b, long mod){ long res = 1; while (b != 0){ if ((b & 1) != 0){ res = quickMul(res, a, mod); } b >>= 1; a = quickMul(a, a, mod); } return res; }
阅读全文
0 0
- 挑战程序竞赛系列(15):2.6快速幂运算
- 挑战程序竞赛系列(13):2.6辗转相除法
- 挑战程序竞赛系列(14):2.6素数
- 挑战程序竞赛系列(30):3.4矩阵的幂
- 挑战程序竞赛系列(38):4.1模运算的世界(1)
- 挑战程序竞赛系列(39):4.1模运算的世界(2)
- 挑战程序竞赛系列(40):4.1模运算的世界(3)
- 挑战程序竞赛系列(42):4.1模运算的世界(4)
- 《挑战程序设计竞赛》2.6.3 数学问题-快速幂运算 POJ1995
- 挑战程序竞赛系列(81):4.3 LCA(1)
- 挑战程序竞赛系列(82):4.3 LCA(2)
- 挑战程序竞赛系列(1):2.3动态规划
- 挑战程序竞赛系列(4):2.1深度优先搜索
- 挑战程序竞赛系列(5):2.1广度优先搜索
- 挑战程序竞赛系列(6):2.1穷尽搜索
- 挑战程序竞赛系列(9):2.4优先队列
- 挑战程序竞赛系列(10):2.4并查集
- 挑战程序竞赛系列(11):2.5最短路径
- ZKFailoverController( zkfc)介绍
- Python爬虫利器:BeautifulSoup库
- php中多维数组排序
- JS为什么有时候要做两次encodeURI
- JDK8-时间API(十)
- 挑战程序竞赛系列(15):2.6快速幂运算
- 使用neo4j shell命令行工具时遭遇“connection refused” error的解决方法(草稿版)
- MongoDB--架构搭建(主从、副本集)之主从
- join连接表时是先join还是先where
- Codeforces 760B Frodo and pillows
- Secure CRT8.1.3安装及破解
- 配置Grub2实现串口终端控制Linux系统
- Spark本地开发与远程调试环境搭建
- IntelliJ IDEA 修正错误,类似eclipse那样