optimalize gravity algo