Given a number N, the task is to find the number of ways N can be partitioned, i.e. the number of ways that N can be expressed as a sum of positive integers.
Note: N should also be considered itself a way to express it as a sum of positive integers.
Input: N = 5
5 can be partitioned in the following ways:
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
Input: N = 10
This post has been already discussed in Ways to write n as sum of two or more positive integers. In this post, an efficient approach is discussed.
Approach(Using Euler’s recurrence):
If p(n) is the number of partitions of N, then it can be generated by the following generating function:
Using this formula and Euler’s pentagonal number theorem, we can derive the following recurrence relation for p(n): (Check the Wikipedia article for more details)
where k = 1, -1, 2, -2, 3, -3, … and p(n) = 0 for n < 0.
Below is the implementation of above approach:
Time Complexity: O(N√N)
Space Complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Ways to write n as sum of two or more positive integers
- Print all possible ways to write N as sum of two or more positive integers
- Number of ways in which N can be represented as the sum of two positive integers
- Number of ways to write N as a sum of K non-negative integers
- Divide two integers without using multiplication, division and mod operator | Set2
- Find K distinct positive odd integers with sum N
- Find all the possible remainders when N is divided by all positive integers from 1 to N+1
- Check whether product of integers from a to b is positive , negative or zero
- Find n positive integers that satisfy the given equations
- Count of digits after concatenation of first N positive integers
- Represent (2 / N) as the sum of three distinct positive integers of the form (1 / m)
- Maximum number of distinct positive integers that can be used to represent N
- Check whether a number can be represented as sum of K distinct positive integers
- Number of arrays of size N whose elements are positive integers and sum is K
- Count positive integers with 0 as a digit and maximum 'd' digits
- Longest alternating subsequence in terms of positive and negative integers
- Count of ways to write N as a sum of three numbers
- Count ways to express even number ‘n’ as sum of even integers
- Number of ways to form a heap with n distinct integers
- Ways to form an array having integers in given range such that total sum is divisible by 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.