File tree Expand file tree Collapse file tree 1 file changed +67
-2
lines changed Expand file tree Collapse file tree 1 file changed +67
-2
lines changed Original file line number Diff line number Diff line change
1
+ ## [ Newton's Method] ( http://en.wikipedia.org/wiki/Newton%27s_method )
2
+
3
+ This is copied from my friend Newton.
4
+
5
+ Then I wrote this code:
6
+
7
+ ```
8
+ public int sqrt(int x) {
9
+ if(x < 0) return -1;
10
+ if(x == 0) return 0;
11
+
12
+ // x/t + t = 2t
13
+ double t = (double)x;
14
+ double tt = 0;
15
+ while( (int)tt - (int)t != 0 ){
16
+ tt = t;
17
+ t = (x/t + t) /2;
18
+
19
+ }
20
+
21
+ return (int)tt;
22
+ }
23
+ ```
24
+
25
+ ## Programming Way
26
+
27
+ Well, I replaced the mathematical way finally, maybe, I think I should do this in programming way.
28
+
29
+ ### Brute Force
30
+
31
+ Search through ` 1..x ` , find the ` i ` , such that ` i^2 == x ` or ` i^2 < x < (i + 1)^2 ` .
32
+
33
+
34
+ ### Binary Search
35
+
36
+ As we can brute force, and ` 1..x ` is obviously ordered, we can do it by applying binary search pattern.
37
+
38
+
39
+ ```
40
+ treat 1..x as the content of an array[0..x-1]
41
+
42
+
43
+ while s < e
44
+
45
+ m = (s + e) / 2
46
+
47
+ if (m + 1)^2 == x
48
+ return m + 1
49
+
50
+ if (m + 1)^2 < x < (m + 1 + 1)^2
51
+ return m + 1
52
+
53
+ if x < (m + 1)^2
54
+ e = m
55
+ else
56
+ s = m + 1
57
+ ```
58
+
59
+ #### Overflow
60
+
61
+ The testcases contain some large numbers like ` Integer.MAX_VALUE ` , code will fail due to overflow.
62
+
63
+ To avoid this, change any ` + ` and ` * ` to ` - ` and ` / `
64
+
65
+ * ` m = (s + e) / 2 ` -> ` m = (e - s) / 2 + s `
66
+ * ` (m + 1)^2 == x ` -> ` x / (m + 1) == (m + 1) `
67
+
1
68
2
- ## TODO
3
- * write down thinking
4
69
You can’t perform that action at this time.
0 commit comments