File tree 4 files changed +86
-0
lines changed
4 files changed +86
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include " solution.hpp"
2
+
3
+ #include < cmath>
4
+ #include < benchmark/benchmark.h>
5
+
6
+ float Q_rsqrt ( float number )
7
+ {
8
+ long i;
9
+ float x2, y;
10
+ const float threehalfs = 1 .5F ;
11
+
12
+ x2 = number * 0 .5F ;
13
+ y = number;
14
+ i = * ( long * ) &y; // evil floating point bit level hacking
15
+ i = 0x5f3759df - ( i >> 1 ); // what the fuck?
16
+ y = * ( float * ) &i;
17
+ y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
18
+ // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
19
+
20
+ #ifndef Q3_VM
21
+ #ifdef __linux__
22
+ assert ( !isnan (y) ); // bk010122 - FPE?
23
+ #endif
24
+ #endif
25
+ return y;
26
+ }
27
+
28
+
29
+ static void BM_mySqrt (benchmark::State& state) {
30
+ auto s = std::make_shared<Solution>();
31
+ for (auto _ : state) {
32
+ s->mySqrt (1233422 .0f );
33
+ }
34
+ }
35
+
36
+ static void BM_sqrt (benchmark::State& state){
37
+ for (auto _ : state) {
38
+ std::sqrt (1233422 .0f );
39
+ }
40
+ }
41
+
42
+ static void BM_Qsqrt (benchmark::State& state){
43
+ for (auto _ : state) {
44
+ Q_rsqrt (1233422 .0f );
45
+ }
46
+ }
47
+
48
+ // BENCHMARK(BM_mySqrt);
49
+ BENCHMARK (BM_sqrt);
50
+ BENCHMARK (BM_Qsqrt);
51
+ BENCHMARK_MAIN ();
Original file line number Diff line number Diff line change
1
+ #include " leetcode.hpp"
2
+ using namespace std ;
3
+
4
+ class Solution {
5
+ public:
6
+ int mySqrt (int x) {
7
+ int L = 0 ;
8
+ int R = x;
9
+ int ans = -1 ;
10
+ while (L <= R){
11
+ long mid = L + (R - L)/2 ;
12
+ if (mid * mid <= x){
13
+ ans = mid;
14
+ L = mid + 1 ;
15
+ }else {
16
+ R = mid - 1 ;
17
+ }
18
+ }
19
+ return ans;
20
+ };
21
+ };
Original file line number Diff line number Diff line change
1
+ #include " solution.hpp"
2
+
3
+ #define CATCH_CONFIG_MAIN
4
+ #include < catch2/catch.hpp>
5
+
6
+ TEST_CASE (__FILE__){
7
+ auto s = std::make_shared<Solution>();
8
+
9
+ SECTION (" example" ){
10
+ REQUIRE (s->mySqrt (4 ) == 2 );
11
+ REQUIRE (s->mySqrt (8 ) == 2 );
12
+ }
13
+ }
Original file line number Diff line number Diff line change @@ -43,6 +43,7 @@ define_target("serialize-and-deserialize-binary-tree")
43
43
define_target (" merge-intervals" )
44
44
define_target (" binary-search" )
45
45
define_target (" guess-number-higher-or-lower" )
46
+ define_target (" sqrtx" )
46
47
47
48
48
49
task (" problem" )
You can’t perform that action at this time.
0 commit comments