code from The Algorithm Design Manual by Steven Skiena