数论问题的几个工具函数
2012-12-21 23:03
309 查看
包括求最大公约数、指数运算求模、高斯 φ 函数 、模运算乘法逆的几个工具函数:
public class NumberTheoryUtil { // 用于返回结果 使 ax + by = d public static class Result { int a; int b; int d; public Result(int a, int b, int d) { this.a = a; this.b = b; this.d = d; } } // 求 x 和 y 的最大公约数 d 以及 a 和 b 使 ax+by=d 且 |a|+|b| 最小 public static Result gcd(int x, int y) { if ( x%y == 0 ) { return new Result(0,1,y); } else { Result res = gcd(y,x%y); return new Result(res.b, res.a-res.b*x/y, res.d); } } // 求模 a^p mod n public static int expmod(int a, int p, int n) { if ( p == 0 ) { return 1; } else if ( p%2 ==0 ) { int m = expmod(a,p/2,n); return (m*m)%n; } else { int m = expmod(a,(p-1)/2, n); return (m*m*a)%n; } } // 求小于等于 n 且与 n 互素的自然数的数目,即高斯函数 φ(n) // phi(n)=n(1-1/p1)(1-1/p2)...(1-1/pk) public static int phi(int n) { int m = (int)Math.sqrt(n+0.5); int r = n; for ( int i=2; i<=m; i++ ) { if ( n%i == 0 ) r = r*(i-1)/i; while (n%i==0) n=n/i; } return r; } // 求即高斯函数 φ(k) k = 1,2,...,n public static int[] phi2(int n) { int[] phi = new int[n+1]; for ( int i=2; i<=n; i++ ) { if ( phi[i] == 0 ) { for ( int j=i; j<=n; j+=i ) { if ( phi[j] == 0 ) phi[j] = j; phi[j] = phi[j]*(i-1)/i; } } } return phi; } // 求 模 n 运算下 x 的乘法逆 y 使 xy mod n = 1,-1 表示无乘法逆 public static int opposite(int x, int n) { Result res = gcd(x,n); if ( res.d == 1 ) { return (res.a + n)%n; } else { return -1; } } }
相关文章推荐
- 工作笔记-关于工具函数的编写问题
- 网易面试题之小易是一个数论爱好者,并且对于一个数的奇数约数十分感兴趣。一天小易遇到这样一个问题: 定义函数f(x)为x最大的奇数约数,x为正整数。 例如:f(44) = 11. 现在给出一个N,需要求
- 日常工作问题总结(三十一)windows获取路径的几个函数GetCurrentDirectory,GetModuleFileName,GetFullPathName
- JS和jquery的几个令人迷惑的问题之四-函数
- 使用sqlldr工具中遇到的几个问题
- CSS盒模型里面的几个宽度问题:offsetWidth,clientWidth,scrollWidth以及jquery的.width()函数
- scanf函数值得注意的几个问题
- 网易面试题之小易是一个数论爱好者,并且对于一个数的奇数约数十分感兴趣。一天小易遇到这样一个问题: 定义函数f(x)为x最大的奇数约数,x为正整数。 例如:f(44) = 11. 现在给出一个N,需要求
- 初学C的函数过程的几个问题
- 处理菱形继承问题&&实现一个虚函数的覆盖及调用&&实现以下几个类的成员函数
- 解决中文问题的几个常用的函数
- 关于C51的中断函数要注意的几个问题
- C语言编写字符串拷贝函数应注意的几个问题
- 利用函数申请内存的几个问题
- 关于C51的中断函数要注意的几个问题
- 【python】几个常用工具函数
- C++数组作为函数参数的几个问题(转)
- 常用工具函数整理(好多数论什么的公式)
- 几个java工具函数
- day04之链表不带环相交+带环相交问题+fork函数输出几个短线