fork(1) download
  1. public class Main {
  2. private static final double TOLERANCE = 1e-10;
  3. public int mySqrt(int x) {
  4. if (x < 2)
  5. return x;
  6. double lowerBound = 0.0, upperBound = x, midPoint = 0.0;
  7. while (upperBound - lowerBound >= TOLERANCE) {
  8. midPoint = lowerBound + (upperBound - lowerBound) / 2;
  9. double square = Math.pow(midPoint, 2);
  10. if (Double.compare(square, x) < 0)
  11. lowerBound = midPoint;
  12. else if (Double.compare(square, x) > 0)
  13. upperBound = midPoint;
  14. else
  15. return (int) midPoint;
  16. }
  17. return (int) midPoint;
  18. }
  19. public static void main(final String[] args){
  20. final Main main = new Main();
  21. final int[] tests = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 24, 25, 26};
  22. for(final int test: tests){
  23. System.out.format("Floor sqrt(%d) = %d%n", test, main.mySqrt(test));
  24. }
  25. }
  26. }
Success #stdin #stdout 0.08s 34260KB
stdin
Standard input is empty
stdout
Floor sqrt(1) = 1
Floor sqrt(2) = 1
Floor sqrt(3) = 1
Floor sqrt(4) = 2
Floor sqrt(5) = 2
Floor sqrt(6) = 2
Floor sqrt(7) = 2
Floor sqrt(8) = 2
Floor sqrt(9) = 3
Floor sqrt(10) = 3
Floor sqrt(24) = 4
Floor sqrt(25) = 5
Floor sqrt(26) = 5