Custom solution to finding the length of a cycle