Algorithm fixed to avoid loops