Improve performance of Python/Ruby's problem 12.