赞
踩
- //mark!
- public static boolean isPrime(int x) {
- if(x<2)return false;
- //i <= sqrt(x) <=> i*i <= x
- for(int i=2;i*i<=x;i++) {
- if(x%i==0)return false;
- }
- return true;
- }
- //sqrt 牛顿迭代法: d*d = n => f(Xn) = Xn*Xn-n;Xn+1 = Xn - f(Xn)/f`(Xn)
- //设f(Xn)=0,迭代求出Xn
- public static double sqrt(double x) {
- if(x<0.0)return Double.NaN;
- double err = 1e-15;
- double t = x;
- //while(abs(t*t-x)>err) {
- // t = (t+x/t)/2.0;
- //}
- //mark!
- //Xn*Xn-n = 0 <=> Xn-n/Xn = 0 <=> Xn-n/Xn = 0*Xn
- while(abs(t-x/t)>err*t) {
- t = (t+x/t)/2.0;
- }
- return t;
- }
- LogUtil.log(MathUtil.isPrime(9));
- LogUtil.log(MathUtil.isPrime(5));
- LogUtil.log(MathUtil.isPrime(95));
- LogUtil.log(MathUtil.sqrt(2));
- LogUtil.log(MathUtil.sqrt(3));
- LogUtil.log(MathUtil.sqrt(4));
- LogUtil.log(MathUtil.sqrt(5));
- false
- true
- false
- 1.414213562373095
- 1.7320508075688772
- 2.0
- 2.23606797749979
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。