-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSquareRootCalculation.java
More file actions
41 lines (35 loc) · 1.16 KB
/
Copy pathSquareRootCalculation.java
File metadata and controls
41 lines (35 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.*;
public class SquareRootCalculation {
public static void main(String[] args) {
int num;
Scanner in = new Scanner(System.in);
// Prompt the user to input a positive integer
System.out.print("Input a positive integer: ");
int n = in.nextInt();
// Print a message indicating the calculation about to take place
System.out.printf("Square root of %d is: ", n);
// Call the sqrt method to calculate the square root and print the result
System.out.println(sqrt(n));
}
// Method to calculate the square root of a number
private static int sqrt(int num) {
if (num == 0 || num == 1) {
return num;
}
int a = 0;
int b = num;
// Perform a binary search to find the square root
while (a <= b) {
int mid = (a + b) >> 1;
if (num / mid < mid) {
b = mid - 1;
} else {
if (num / (mid + 1) <= mid) {
return mid;
}
a = mid + 1;
}
}
return a;
}
}