compile_time_power_of_number.cpp
This commit is contained in:
89
puzzles/interviews/training/compile_time_power_of_number.cpp
Normal file
89
puzzles/interviews/training/compile_time_power_of_number.cpp
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
/*
|
||||||
|
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||||
|
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||||
|
VIM-: let b:cppflags=g:Iboost.g:Itbb
|
||||||
|
VIM-: let b:ldflags=g:Lboost.g:Ltbb
|
||||||
|
VIM-: let b:ldlibpath=g:Bboost.g:Btbb
|
||||||
|
VIM-: let b:argv=""
|
||||||
|
*/
|
||||||
|
#include <iostream>
|
||||||
|
#include <exception>
|
||||||
|
#include <chrono>
|
||||||
|
|
||||||
|
|
||||||
|
template <int N>
|
||||||
|
struct power_of
|
||||||
|
{
|
||||||
|
enum {
|
||||||
|
value = power_of<(N+1)/2>::value * 2
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
template <>
|
||||||
|
struct power_of<2>
|
||||||
|
{
|
||||||
|
enum {
|
||||||
|
value = 2
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
template <>
|
||||||
|
struct power_of<1>
|
||||||
|
{
|
||||||
|
enum {
|
||||||
|
value = 1
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
template <>
|
||||||
|
struct power_of<0>
|
||||||
|
{
|
||||||
|
enum {
|
||||||
|
value = 0
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
template <int N>
|
||||||
|
void test()
|
||||||
|
{
|
||||||
|
std::cout << N << "=> " << power_of<N>::value <<std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main ( void )
|
||||||
|
{try{
|
||||||
|
auto begin = std::chrono::high_resolution_clock::now();
|
||||||
|
|
||||||
|
|
||||||
|
test<0>();
|
||||||
|
test<1>();
|
||||||
|
test<2>();
|
||||||
|
test<3>();
|
||||||
|
test<4>();
|
||||||
|
test<5>();
|
||||||
|
test<6>();
|
||||||
|
test<7>();
|
||||||
|
test<8>();
|
||||||
|
test<9>();
|
||||||
|
test<127>();
|
||||||
|
test<128>();
|
||||||
|
test<129>();
|
||||||
|
//......
|
||||||
|
|
||||||
|
auto end = std::chrono::high_resolution_clock::now();
|
||||||
|
std::chrono::duration<double> seconds = end - begin;
|
||||||
|
std::cout << "Time: " << seconds.count() << std::endl;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
catch ( const std::exception& e )
|
||||||
|
{
|
||||||
|
std::cerr << std::endl
|
||||||
|
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
catch ( ... )
|
||||||
|
{
|
||||||
|
std::cerr << std::endl
|
||||||
|
<< "unknown exception." << std::endl;
|
||||||
|
return 1;
|
||||||
|
}}
|
||||||
|
|
||||||
Reference in New Issue
Block a user