Using different algorithm for better speed, thanks to @g-rocket for tip