Problem #12 (optimized)