当前位置:   article > 正文

判断素数和牛顿迭代法求平方根

判断素数和牛顿迭代法求平方根
  1. //mark!
  2. public static boolean isPrime(int x) {
  3. if(x<2)return false;
  4. //i <= sqrt(x) <=> i*i <= x
  5. for(int i=2;i*i<=x;i++) {
  6. if(x%i==0)return false;
  7. }
  8. return true;
  9. }
  10. //sqrt 牛顿迭代法: d*d = n => f(Xn) = Xn*Xn-n;Xn+1 = Xn - f(Xn)/f`(Xn)
  11. //设f(Xn)=0,迭代求出Xn
  12. public static double sqrt(double x) {
  13. if(x<0.0)return Double.NaN;
  14. double err = 1e-15;
  15. double t = x;
  16. //while(abs(t*t-x)>err) {
  17. // t = (t+x/t)/2.0;
  18. //}
  19. //mark!
  20. //Xn*Xn-n = 0 <=> Xn-n/Xn = 0 <=> Xn-n/Xn = 0*Xn
  21. while(abs(t-x/t)>err*t) {
  22. t = (t+x/t)/2.0;
  23. }
  24. return t;
  25. }
  1. LogUtil.log(MathUtil.isPrime(9));
  2. LogUtil.log(MathUtil.isPrime(5));
  3. LogUtil.log(MathUtil.isPrime(95));
  4. LogUtil.log(MathUtil.sqrt(2));
  5. LogUtil.log(MathUtil.sqrt(3));
  6. LogUtil.log(MathUtil.sqrt(4));
  7. LogUtil.log(MathUtil.sqrt(5));
  1. false
  2. true
  3. false
  4. 1.414213562373095
  5. 1.7320508075688772
  6. 2.0
  7. 2.23606797749979

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/326283?site
推荐阅读
相关标签
  

闽ICP备14008679号