Implementing Integer Open-Form Java Edition without Library Functions

Keywords: Java less

The first type of question:

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.

The square sqrt of a number x must be between 0 and x, and it satisfies sqrt == x / sqrt. Binary lookup can be used to find sqrt between 0 and X.

For x = 8, it starts with 2.82842... and should return 2 instead of 3. When the loop condition is l<= h and the loop exits, h is always 1 less than l, that is, h = 2, l = 3, so the final return value should be h instead of 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;
    }
}

 

The second type of question:

Decimals need to be retained
Input: 2
Output: 1.414

Input: 5
Output: 2.236

This type of problem is solved by Newton's iteration method, which is accurate to the last three decimal points.

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"; //Formatting
        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);//Newton's iteration formula
        while (Math.abs(x2 - x1) > 1e-4) {
            x1 = x2;
            x2 = x1 / 2.0 + a / (2 * x1);
        }
        return x2;
    }
}

 

Posted by connex on Wed, 02 Oct 2019 14:51:55 -0700