Fixed bug of counter overflow in the distances algorithm