Solution to problem 23, super slow. Could be faster
FIX bug