Correct solution to problem B. Issue was integer overflow