Improved solution to the CountFactors problem