Permutation formula n!/(n-r)!

As @DNF said, to avoid overflow you need to convert to BigInt before computing factorials. It’s easiest to do this once, before the subsequent calls:

function combinations(n, r)
    nbig, rbig = BigInt(n), BigInt(r) # convert to BigInt to avoid overflow
    x = factorial(nbig)
    z = factorial(rbig)
    t = factorial(nbig - rbig)
    final = div(x, t * z) # use integer division, not /
    return final
end

Note that this corresponds to the built-in binomial(n, r) function.

There are more efficient ways of computing it by canceling terms from the factorials in the numerator and denominator analytically, as @DNF mentioned, but you want to focus on correctness before worrying about performance.

1 Like