/* VIM: let b:cf5build="clang -std=c++20 -O2 -pthread -lstdc++ -I. {SRC} -o {OUT}" VIM: let b:cf5run="{OUT}" */ #include #include #include /* This is from "The C++ Programming Language, Fourth Edition * by Bjarne Stroustrup"*/ constexpr int sqrt2(int x, int i = 3, int i_sq = 1){ return i_sq <= x ? sqrt2(x, i+2, i_sq + i) : i/2-1; } /* My simplified version: * Basically sum(1+2*i) where i==0..n-1 == n^2 */ constexpr int sqrt(int x, int i = 1, int i_sq = 1){ return i_sq <= x ? sqrt(x, i+1, i_sq + (1+2*i)) : i-1; } int main ( void ) {try{ auto begin = std::chrono::high_resolution_clock::now(); std::cout << "sqrt(-1)=" << sqrt(-1) << " vs " << sqrt2(-1) << std::endl; std::cout << "sqrt(0)=" << sqrt(0) << " vs " << sqrt2(0) << std::endl; std::cout << "sqrt(1)=" << sqrt(1) << " vs " << sqrt2(1) << std::endl; std::cout << "sqrt(2)=" << sqrt(2) << " vs " << sqrt2(2) << std::endl; std::cout << "sqrt(3)=" << sqrt(3) << " vs " << sqrt2(3) << std::endl; std::cout << "sqrt(4)=" << sqrt(4) << " vs " << sqrt2(4) << std::endl; std::cout << "sqrt(5)=" << sqrt(5) << " vs " << sqrt2(5) << std::endl; std::cout << "sqrt(6)=" << sqrt(6) << " vs " << sqrt2(6) << std::endl; std::cout << "sqrt(9)=" << sqrt(9) << " vs " << sqrt2(9) << std::endl; std::cout << "sqrt(16)=" << sqrt(16) << " vs " << sqrt2(16) << std::endl; std::cout << "sqrt(24)=" << sqrt(24) << " vs " << sqrt2(24) << std::endl; std::cout << "sqrt(25)=" << sqrt(25) << " vs " << sqrt2(25) << std::endl; std::cout << "sqrt(26)=" << sqrt(26) << " vs " << sqrt2(26) << std::endl; std::cout << "sqrt(36)=" << sqrt(36) << " vs " << sqrt2(36) << std::endl; //...... auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration 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; }}