Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating the partitions of a number

I needed an algorithm to generate all possible partitions of a positive number, and I came up with one (posted as an answer), but it's exponential time.

The algorithm should return all the possible ways a number can be expressed as the sum of positive numbers less than or equal to itself. So for example for the number 5, the result would be:

  • 5
  • 4+1
  • 3+2
  • 3+1+1
  • 2+2+1
  • 2+1+1+1
  • 1+1+1+1+1

So my question is: is there a more efficient algorithm for this?

EDIT: Question was titled "Sum decomposition of a number", since I didn't really know what this was called. ShreevatsaR pointed out that they were called "partitions," so I edited the question title accordingly.

like image 277
Can Berk Güder Avatar asked Dec 30 '08 16:12

Can Berk Güder


People also ask

What is the generating function for the number of partitions?

Theorem: k(n) is also the number of partitions of n into distinct, odd parts. We begin with the generating function P(x) = ∑p(n)xn which counts all partitions of all numbers n, with weight xn for a partition of n.

How do you find the partition of a number?

The number of partitions of n is given by the partition function p(n). So p(4) = 5. The notation λ ⊢ n means that λ is a partition of n. Partitions can be graphically visualized with Young diagrams or Ferrers diagrams.

How do you calculate the number of partitions in a set?

In general, Bn is the number of partitions of a set of size n. A partition of a set S is defined as a family of nonempty, pairwise disjoint subsets of S whose union is S. For example, B3 = 5 because the 3-element set {a, b, c} can be partitioned in 5 distinct ways: { {a}, {b}, {c} }

How many partitions does 5 have?

Typically a partition is written as a sum, not explicitly as a multiset. Using the usual convention that an empty sum is 0, we say that p0=1. Example 3.3. 2 The partitions of 5 are 54+13+23+1+12+2+12+1+1+11+1+1+1+1.


1 Answers

It's called Partitions. [Also see Wikipedia: Partition (number theory).]

The number of partitions p(n) grows exponentially, so anything you do to generate all partitions will necessarily have to take exponential time.

That said, you can do better than what your code does. See this, or its updated version in Python Algorithms and Data Structures by David Eppstein.

like image 177
ShreevatsaR Avatar answered Sep 28 '22 19:09

ShreevatsaR