After crashing three times, found a workable solution, if not an elegant one. Learned some number theory.