introduce some short-circuiting to speed up algorithm. use recursion.