Use recursive function instead of loop. The runtime error does not occur now. But it still results in timeup.