performance/perf-cpp/scripts/ch5.cc

51 lines
1.2 KiB
C++

#include <cassert>
#include <cmath>
#include <concepts>
#include <iomanip>
#include <iostream>
#include <string>
#include <string_view>
template <std::integral T>
T binexp(T base, T exponent, T mod) {
assert(mod > 0 && exponent > 0);
T product{1};
T multiplier{base % mod};
while (exponent > 0) {
if ((exponent & 1) != 0) {
product = (multiplier * product) % mod;
}
multiplier = (multiplier * multiplier) % mod;
exponent >>= 1;
}
return product;
}
int main() {
using namespace std::string_view_literals;
std::string S{"hello"};
std::string_view s{S};
S.~basic_string();
// double ub - free + string view dereferencing destroyed object
// std::cout << s << '\n' ;
std::cout << -5 / 2 << '\n';
using namespace std;
long double ld = pow((long double)10, 18); // computed in floating point
long long ll = (long long)ld; // cast back to integer
cout << fixed << setprecision(0);
cout << "pow(10,18) as long double: " << ld << "\n";
cout << "cast to long long: " << ll << "\n";
cout << "Should be exactly: " << 1000000000000000000LL << "\n";
std::cout << binexp(2, 5, 5);
return 0;
}