invfact is simply a precomputed array of modular multiplicative inverses for each value of i!. See here if you don’t know what that is (shameless self-promotion). Because \dbinom{n}{k} = \dfrac{n!}{(n - k)! \cdot k!}, we need to quickly “divide” by (n - k)! and k!, these precomputed inverses let us do that.
In brief, this comment shows how I would write nCk. nPk can be calculated by removing ifact[k] from the function. All of this preprocessing can be done in O(n).