Hướng dẫn integer square root python
Inspired by all answers, decided to implement in pure C++ several best methods from these answers. As everybody knows C++ is always faster than Python. To glue C++ and Python I used Cython. It allows to make out of C++ a Python module and then call C++ functions directly from Python functions. Also as complementary I provided not only Python-adopted code, but pure C++ with tests too. Here are timings from pure C++ tests:
and same C++ functions but as adopted Python module have timings:
My Cython-C++ is nice in a sence as a framework for those people who want to write and test his own C++ method from Python directly. As you noticed in above timings as example I used following methods:
Regarding compiling C++/Cython code, I used GMP library. You
need to install it first, under Linux it is easy through Under Windows easiest is to install really great program VCPKG, this is software Package Manager, similar to APT in Linux. VCPKG compiles all packages from sources using Visual Studio (don't forget to
install Community version of Visual Studio). After installing VCPKG you can install GMP by After GMP is installed under Windows please edit my Python code and replace path to include directory and library file. VCPKG at the end of installation should show you path to ZIP file with GMP library, there are .lib and .h files. You may notice in Python code that I also designed special handy If you have any questions or suggestions, or something doesn't work on your PC, please write in comments. Below first I show code in Python, afterwards in C++. See
and C++: Try it online! |