solution to problem 5. slow but it seems to run within 1 minute. will work on a faster solution later