I changed math.pow to d*d for efficiency