Highly optimized and debugged solution to problem 49 plus some others