optimized factorial function