Problem (Integer Partitions): Given an integer , in how many ways can the integer be expressed as a sum of integers?
Take I: Dynamic Programming
Let's name the function we want to compute . Our first stab would be to think of something like this:
However, this is not quite correct. We're overcounting the partitions. (Think why)
To avoid overcounting, we instead ask: Given two integers and , in how many ways can be partitioned using integers less than or equal to ?
1 2 3 4 5 6 7 8 9
Take II: Generating Functions
(Influenced by Math.Combinat)
It is not hard to see that what we want is the coefficient of in .
Now, consider the following sequence of power series converging to .
In general, .
At this point, let us switch to the infinite list representations of the power series. We have:
1 2 3 4 5 6 7 8
Notice that the first terms of can be inherited from those of , and are the same as those of . To express the same idea in Haskell, we drop the first terms in the power series and get
This motivates us to exploit the lazyness of haskell and write in terms of , which, by virtue of laziness, has been calculated to a certain extent, already.
Now, we have adequate background to implement g itself:
1 2 3 4 5
It's worth appreceating that the gf solution works really fast as compared to the dynamic programming solution.
Take III: Pentagonal Number Theorem
(I'm hoping someone would explain this better in the comments section.)
Euler's Pentagonal Number Theorem suggests that the denominator of the generating function discussed above could be written as
The numbers used here are Generalized Pentagonal Numbers.
It can be deduced that where the numbers used are generalized Pentagonal Numbers.
1 2 3 4 5 6 7