Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class BinarySearchSqrt {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter a number: ");
- double number = sc.nextInt();// what they want to find sqrt
- // range that we know the answer is in
- double low = 0;
- double high = number;
- // begin guessing
- for (int trial = 0; trial < 100; trial++) {
- double guess = (low + high) / 2;// guess in the middle
- if (guess * guess < number) {
- // guess too low
- low = guess;
- } else if (guess * guess > number) {
- // guess too high
- high = guess;
- } else {
- // perfect guess
- System.out.println(guess);
- return;
- }
- }
- // could not get perfect guess
- System.out.println(low);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement