Advertisement
gelita

square root

Feb 10th, 2020
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.10 KB | None | 0 0
  1.  
  2.   import java.io.*;
  3.   import java.util.*;
  4.  
  5.   class MyCode {
  6.    /*
  7.  * Square Root
  8.  *
  9.  * Given an positive integer, find the square root.*
  10.  *
  11.  * **Parameters**
  12.  * Input: value {Double}
  13.  * Output: {Double}
  14.  *
  15.  * **Constraints**
  16.  * Do not use a native built in method.
  17.  * Ensure the result is accurate to 6 decimal places (0.000001)
  18.  *
  19.  * Time: O(logN)
  20.  * Space: O(1)
  21.  *
  22.  * **Examples**
  23.  * `4 --> 2.0`
  24.  * `98 --> 9.899495`
  25.  * `14856 --> 121.885192
  26.  */
  27.      public static void main (String[] args) {
  28.       Double d =9.0;
  29.       System.out.println(squareRoot(d));  
  30.     }
  31.  
  32.       public static Double squareRoot(Double n) {
  33.         double tempNum;
  34.         double squareRoot = n / 2;
  35.         do {
  36.           tempNum = squareRoot;
  37.           squareRoot = (tempNum + (n / tempNum)) / 2;
  38.         } while ((tempNum - squareRoot) != 0); //once tempNum and squareRoot are equal,
  39.         //continue to format result double
  40.         //multiply by 1,000,000 and divide to round out to 6 places past decimal
  41.         return (double)Math.round(squareRoot * 1000000d) / 1000000d;
  42.       }
  43.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement