added a more optimised code for problem 27