Factorize calculation of the cost