Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- class MyCode {
- /*
- * Square Root
- *
- * Given an positive integer, find the square root.*
- *
- * **Parameters**
- * Input: value {Double}
- * Output: {Double}
- *
- * **Constraints**
- * Do not use a native built in method.
- * Ensure the result is accurate to 6 decimal places (0.000001)
- *
- * Time: O(logN)
- * Space: O(1)
- *
- * **Examples**
- * `4 --> 2.0`
- * `98 --> 9.899495`
- * `14856 --> 121.885192
- */
- public static void main (String[] args) {
- Double d =9.0;
- System.out.println(squareRoot(d));
- }
- public static Double squareRoot(Double n) {
- double tempNum;
- double squareRoot = n / 2;
- do {
- tempNum = squareRoot;
- squareRoot = (tempNum + (n / tempNum)) / 2;
- } while ((tempNum - squareRoot) != 0); //once tempNum and squareRoot are equal,
- //continue to format result double
- //multiply by 1,000,000 and divide to round out to 6 places past decimal
- return (double)Math.round(squareRoot * 1000000d) / 1000000d;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement