-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathsqrt.cpp
93 lines (80 loc) · 1.66 KB
/
sqrt.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* @Author: Chacha
* @Date: 2018-11-26 11:11:37
* @Last Modified by: Chacha
* @Last Modified time: 2021-03-26 18:08:00
*/
/**
* Implement int sqrt(int x).
* Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
* Since the return type is an integer, the decimal digits are truncated
* and only the integer part of the result is returned.
* Source: https://leetcode.com/problems/sqrtx/
*
* Example 1:
* Input: 4
* Output: 2
*
* Example 2:
* Input: 8
* Output: 2
* Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
*/
#include <iostream>
using namespace std;
int sqrt(int x)
{
if (x < 0)
{
return -1;
}
else if (x == 0)
{
return 0;
}
long start = 1;
long end = x;
long mid;
while (start + 1 < end)
{
mid = start + (end - start) / 2;
if (mid * mid == x)
{
return mid;
}
else if (mid * mid > x)
{
end = mid;
}
else
{
start = mid;
}
}
return start;
}
// Babylonian method for finding square roots
int sqrtByBabylonian(int x)
{
if (x == 0)
{
return 0;
}
double preSqrt, curSqrt = x, xFloat = x;
while (true)
{
preSqrt = curSqrt;
curSqrt = (curSqrt + xFloat / curSqrt) / 2;
if (preSqrt == curSqrt)
{
return curSqrt;
}
}
}
int main()
{
int result1 = sqrt(8);
int result2 = sqrtByBabylonian(10);
cout << "Result1 is " << result1 << "\n";
cout << "Result2 is " << result2 << endl;
}