Recursive and mathematical solution - Credit to Jason Hill for mathematical proof