# How to compute nPr in sagemath

edit retag close merge delete

What is nPr?

( 2023-07-15 14:45:44 +0200 )edit

Sort by » oldest newest most voted

The following method avoids computing factorials explicitly, which can be computationally expensive for large values of n and r. Instead, it computes the product of a sequence of values using a generator expression, which is more memory-efficient and faster than computing factorials. You can compute perm(n, r) using a prod function, which is a built-in SageMath function that computes the product of a sequence of values.

See the code:

perm(n, r) = prod(n - i for i in range(r))

more

Hello! I am assuming nPr means "n permutation r". Unfortunately, SageMath doesn't have a command for that purpose. However, if you remember that

$$nPr = \frac{n!}{(n-r)!} = \binom{n}{r}r!,$$

you can make something like this:

perm(n, r) = factorial(n) / factorial(n - r)


or even:

perm(n, r) = binomial(n, r) * factorial(r)


Hope this helps!

more

Permutations(n,r).cardinality() ?

( 2023-07-15 22:12:11 +0200 )edit

Or binomial(n,r)*factorial(r) ?

( 2023-07-16 20:53:45 +0200 )edit

To my surprise, the former is about 12 times faster than the latter :

sage: %timeit Permutations(5,3).cardinality()
2.31 µs ± 450 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
sage: sage: %timeit binomial(5,3)*factorial(3)
27.3 µs ± 860 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)


Go figure...

( 2023-07-16 20:59:50 +0200 )edit