Complete implementation of Length and Ancestor calculation. Implement caching so that consecutive calls to Length or Ancestor with same arguments will reuse cached results.