Completed Exercise 5. Slight optimization of torus distance function in Exercise 4