Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class BinarySearchSqrt {
  4.  
  5. public static void main(String[] args) {
  6. Scanner sc = new Scanner(System.in);
  7. System.out.println("Enter a number: ");
  8.  
  9. double number = sc.nextInt();// what they want to find sqrt
  10.  
  11. // range that we know the answer is in
  12. double low = 0;
  13. double high = number;
  14.  
  15. // begin guessing
  16. for (int trial = 0; trial < 100; trial++) {
  17. double guess = (low + high) / 2;// guess in the middle
  18.  
  19. if (guess * guess < number) {
  20. // guess too low
  21. low = guess;
  22. } else if (guess * guess > number) {
  23. // guess too high
  24. high = guess;
  25. } else {
  26. // perfect guess
  27. System.out.println(guess);
  28. return;
  29. }
  30. }
  31.  
  32. // could not get perfect guess
  33. System.out.println(low);
  34. }
  35.  
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement