Debugged code, working perfectly for small n