Solve #45, pretty fast but not fully optimized.