C++ implementation of the more-efficient algorithm