-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathdifferent_summands.py
43 lines (36 loc) · 990 Bytes
/
different_summands.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Uses python3
import sys
def optimal_summands(n):
"""Pairwise Distinct Summands.
The goal of this problem is to represent a given positive integer n as
a sum of as many pairwise distinct positive integers as possible.
Samples:
>>> optimal_summands(6)
3
1 2 3
>>> optimal_summands(8)
3
1 2 5
"""
summands = [1]
n -= 1
while n:
last_element = summands[-1]
# Save move: check whether the incremented last element can be used as
# the next summand.
if (last_element + 1) * 2 <= n:
n -= last_element + 1
summands.append(last_element + 1)
else:
if last_element >= n:
n += summands.pop()
summands.append(n)
n = 0
return summands
if __name__ == "__main__":
input = sys.stdin.read()
n = int(input)
summands = optimal_summands(n)
print(len(summands))
for x in summands:
print(x, end=" ")