Debugged solution, working well for small n's