Improved Hw 5.1 solution