need to do terminating condition and last p computation