Finished version - works for both large and small inputs