Processing math: 0%
Ask Your Question
1

How to compute nPr in sagemath

asked 1 year ago

Sambit gravatar image

How to compute nPr in sagemath? Please help

Preview: (hide)

Comments

What is nPr?

Max Alekseyev gravatar imageMax Alekseyev ( 1 year ago )

2 Answers

Sort by » oldest newest most voted
1

answered 1 year ago

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))
Preview: (hide)
link
0

answered 1 year ago

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!

Preview: (hide)
link

Comments

Permutations(n,r).cardinality() ?

Max Alekseyev gravatar imageMax Alekseyev ( 1 year ago )

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

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 1 year ago )

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 ( 1 year ago )

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: 1 year ago

Seen: 396 times

Last updated: Jul 21 '23