Solve #40, for the general case and super fast.