improved speed on problem 4