Ask Your Question
1

How to compute nPr in sagemath

asked 2023-07-15 13:42:28 +0100

Sambit gravatar image

How to compute nPr in sagemath? Please help

edit retag flag offensive close merge delete

Comments

What is nPr?

Max Alekseyev gravatar imageMax Alekseyev ( 2023-07-15 14:45:44 +0100 )edit

2 Answers

Sort by » oldest newest most voted
1

answered 2023-07-21 10:29:41 +0100

lisbeth gravatar image

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))
edit flag offensive delete link more
0

answered 2023-07-15 16:20:08 +0100

dsejas gravatar image

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!

edit flag offensive delete link more

Comments

Permutations(n,r).cardinality() ?

Max Alekseyev gravatar imageMax Alekseyev ( 2023-07-15 22:12:11 +0100 )edit

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

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2023-07-16 20:53:45 +0100 )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...

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2023-07-16 20:59:50 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2023-07-15 13:42:28 +0100

Seen: 335 times

Last updated: Jul 21 '23