ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

不用库函数实现整数开方 Java版

2019-08-20 09:35:33  阅读:229  来源: 互联网

标签:开方 Java Scanner System sqrt x2 x1 public 库函数


第一种题型:

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,Scanner,System,sqrt,x2,x1,public,库函数
来源: https://blog.csdn.net/qq_32100465/article/details/99817884

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有