problem #23 optimized