Solution for Problem #14 (optimized ~10x faster)