Improved algorithm to calculate the factorial