首页 / JAVA / 不用库函数实现整数开方 Java版
不用库函数实现整数开方 Java版
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了不用库函数实现整数开方 Java版,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1532字,纯文字阅读大概需要3分钟。
内容图文
![不用库函数实现整数开方 Java版](/upload/InfoBanner/zyjiaocheng/736/bf6ba1f42e564dcd880199099851a738.jpg)
第一种题型:
Input: 4
Output: 2
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.
一个数 x 的开方 sqrt 一定在 0 ~ x 之间,并且满足 sqrt == x / sqrt。可以利用二分查找在 0 ~ x 之间查找 sqrt。
对于 x = 8,它的开方是 2.82842...,最后应该返回 2 而不是 3。在循环条件为 l <= h 并且循环退出时,h 总是比 l 小 1,也就是说 h = 2,l = 3,因此最后的返回值应该为 h 而不是 l。
import java.util.Scanner;
public class Sqrt {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
System.out.print("sqrt(" + a + ") = " );
System.out.println(mySqrt(a));
}
public static int mySqrt(int x) {
if (x <= 1) {
return x;
}
int l = 1, h = x;
while (l <= h) {
int mid = l + (h - l) / 2;
int sqrt = x / mid;
if (sqrt == mid) {
return mid;
} else if (mid > sqrt) {
h = mid - 1;
} else {
l = mid + 1;
}
}
return h;
}
}
第二种题型:
需要保留小数
Input: 2
Output: 1.414
Input: 5
Output: 2.236
这种题型运用牛顿迭代法求解,精确到小数点后三位。
import java.text.DecimalFormat;
import java.util.Scanner;
public class Sqrt {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.000");//格式化
int a = scanner.nextInt();
System.out.print("sqrt(" + a + ") = " );
System.out.println(df.format(sqrt(a)));
}
public static double sqrt(int a) {
double x1 = 1;
double x2;
x2 = x1 / 2.0 + a / (2 * x1);//牛顿迭代公式
while (Math.abs(x2 - x1) > 1e-4) {
x1 = x2;
x2 = x1 / 2.0 + a / (2 * x1);
}
return x2;
}
}
内容总结
以上是互联网集市为您收集整理的不用库函数实现整数开方 Java版全部内容,希望文章能够帮你解决不用库函数实现整数开方 Java版所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。