SQRT (X)
Implementint sqrt(int x)
.
Compute and return the square rootX.
Note ]:
1. Int type may overflow, so multiplication is not allowed. Try to use division.
2. The vast majority of numbers are not open-ended. How can we get close results?
Algorithm ideas:
Train of Thought 1: sequential traversal certainly does not need to be tested. Binary Search is more reliable. The bipartite method is very common in numerical computation and requires proficiency.
The Code is as follows:
Public class solution {public int SQRT (int x) {If (x <= 1) return x = 0? 0: X; int L = 1, R = X/2 + 1; while (L <= r) {int mid = (L + r)/2; if (mid <= x/Mid & (Mid + 1)> X/(Mid + 1) {return mid; // here is a clever use} else if (mid> X/Mid) {r = mid-1;} else {L = Mid + 1 ;}} return 0 ;}}
Idea 2: Newton Iteration Method; relatively tall, please stamp the detailed analysis process here.
The Code is as follows:
1 public int sqrt(int x) { 2 if (x == 0) return 0; 3 double lastY = 0; 4 double y = 1; 5 while (y != lastY) 6 { 7 lastY = y; 8 y = (y + x / y) / 2; 9 }10 return (int)(y);11 }
This question is very good.