You've seen countless variations of this problem all over the place. Sometimes it can be done by complex numbers or ad-hoc methods. But there is a theory behind it! And that theory is RECURSION!