Several Cody problems deal with partitions of an integer, or the ways an integer n can be written as the sum of positive numbers—either all integers up to and including n or a subset of those numbers.
Most of the problems involve counting partitions. Cody Problem 1873 counts the partitions of an integer, while Cody Problem 42918 counts the partitions with a given number of parts. Cody Problem 45429 restricts the parts to primes; Cody Problem 1240 restricts them to U.S. coin denominations; and Cody Problem 54740 restricts them to American football scores.
A couple of problems involves listing partitions. Cody Problem 590 asks us to list one partition of a number, without repeating parts, and Cody Problem 59586 involves listing ways to make a sum in Killer Sudoku.
This problem involves listing all partitions of an integer. For example, 5 = 4+1 = 3+2 = 3+1+1 = 2+2+1 = 2+1+1+1 = 1+1+1+1+1. Notice that rearrangements of a partition are not included.
Write a function to list partitions of an integer. Return the partitions in a cell array and sort them as in the example—i.e., from larger to smaller numbers. For
, the required output is
{[5] [4 1] [3 2] [3 1 1] [2 2 1] [2 1 1 1] [1 1 1 1 1]}
Solution Stats
Problem Comments
6 Comments
Solution Comments
Show comments
Loading...
Problem Recent Solvers5
Suggested Problems
-
List the partitions of an integer
5 Solvers
More from this Author321
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
61, why are you in the test suite... I have a straightforward solution, but it takes 63 seconds on my machine for 61, and times out on Cody too.
My solution takes about 10 seconds on my laptop and 6 seconds on Cody for n = 61. I'm looking forward to seeing solutions from the community, which are usually cleverer and faster than mine.
Thanks, Chris. I took another look and managed to get a faster version that now takes ~5 seconds on my machine for 61.
Chris - This problem is beautifully written! but I need to point out that the example in paragraph 4 for the partitions of the number 5 contains 2 incorrect partitions. The each add up to more than 5. The partitions of 5 given in the last line are, however, correct.
Yikes. Thanks, William!
If we were on the quiz site Sporcle, writing code that correctly computes the 8,118,264 partitions of 75 but mangling simple arithmetic would be an example of Sporclitis. During a quiz involving world capitals starting with W, I wrote down Warsaw, Wellington, and Windhoek but could not come up with the fourth--the capital of my own country.