2019-10-05 01:14:13 -04:00
|
|
|
"""
|
2020-06-16 10:09:19 +02:00
|
|
|
The number of partitions of a number n into at least k parts equals the number of
|
|
|
|
partitions into exactly k parts plus the number of partitions into at least k-1 parts.
|
|
|
|
Subtracting 1 from each part of a partition of n into k parts gives a partition of n-k
|
|
|
|
into k parts. These two facts together are used for this algorithm.
|
2019-10-05 01:14:13 -04:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
2021-08-30 13:36:59 +05:30
|
|
|
def partition(m: int) -> int:
|
|
|
|
memo: list[list[int]] = [[0 for _ in range(m)] for _ in range(m + 1)]
|
2019-10-05 01:14:13 -04:00
|
|
|
for i in range(m + 1):
|
|
|
|
memo[i][0] = 1
|
|
|
|
|
2023-10-08 20:20:53 +05:30
|
|
|
for total in range(m + 1):
|
|
|
|
for largest_num in range(1, m):
|
|
|
|
memo[total][largest_num] += memo[total][largest_num - 1]
|
|
|
|
if total - largest_num > 0:
|
|
|
|
memo[total][largest_num] += memo[total - largest_num - 1][largest_num]
|
2018-03-22 09:33:54 -04:00
|
|
|
|
2019-10-05 01:14:13 -04:00
|
|
|
return memo[m][m - 1]
|
2018-03-22 09:33:54 -04:00
|
|
|
|
2019-10-05 01:14:13 -04:00
|
|
|
if __name__ == "__main__":
|
|
|
|
import sys
|
2018-03-22 09:33:54 -04:00
|
|
|
|
2019-10-05 01:14:13 -04:00
|
|
|
if len(sys.argv) == 1:
|
|
|
|
try:
|
2023-10-08 20:20:53 +05:30
|
|
|
n = int(input("Enter a positive integer: ").strip())
|
|
|
|
if n <= 0:
|
|
|
|
print("Please enter a positive integer.")
|
|
|
|
else:
|
|
|
|
print("Number of ways to partition:", partition(n))
|
2019-10-05 01:14:13 -04:00
|
|
|
except ValueError:
|
2023-10-08 20:20:53 +05:30
|
|
|
print("Please enter a valid positive integer.")
|
2019-10-05 01:14:13 -04:00
|
|
|
else:
|
|
|
|
try:
|
|
|
|
n = int(sys.argv[1])
|
2023-10-08 20:20:53 +05:30
|
|
|
if n <= 0:
|
|
|
|
print("Please pass a positive integer.")
|
|
|
|
else:
|
|
|
|
print("Number of ways to partition:", partition(n))
|
2019-10-05 01:14:13 -04:00
|
|
|
except ValueError:
|
2023-10-08 20:20:53 +05:30
|
|
|
print("Please pass a valid positive integer.")
|