-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsqrt.cpp
More file actions
50 lines (42 loc) · 1.61 KB
/
sqrt.cpp
File metadata and controls
50 lines (42 loc) · 1.61 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
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <chrono>
#include <cmath>
int mySqrt(int x) {
return static_cast<int>(std::pow(x, 0.5));
}
int myFasterSqrt(int x) {
if (x == 0 || x == 1) return x;
int L = 1, R = x / 2;
while (L <= R) {
int M = L + (R - L) / 2;
long long M_squared = static_cast<long long>(M) * M; // Избегаем переполнения
if (M_squared == x)
return M;
else if (M_squared < x)
L = M + 1;
else
R = M - 1;
}
return R;
}
int main() {
int x = 240000000;
// Тест mySqrt
auto start = std::chrono::high_resolution_clock::now();
int result1 = mySqrt(x);
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
std::cout << "mySqrt: " << result1 << " (Time: " << duration.count() << " ns)\n";
// Тест myFasterSqrt
start = std::chrono::high_resolution_clock::now();
int result2 = myFasterSqrt(x);
end = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
std::cout << "myFasterSqrt: " << result2 << " (Time: " << duration.count() << " ns)\n";
// Тест std::sqrt
start = std::chrono::high_resolution_clock::now();
int result3 = static_cast<int>(std::sqrt(x));
end = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
std::cout << "std::sqrt: " << result3 << " (Time: " << duration.count() << " ns)\n";
}