algorithm in C++ and Python