Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Sums of Consecutive Integers

Before anyone says anything, similar and similar. But this is not a dupe.


Some positive integers can be written as the sum of at least two consecutive positive integers. For example, 9=2+3+4=4+5. Write a function that takes a positive integer as its input and prints as its output the longest sequence of increasing consecutive positive integers that sum to it (any format is acceptable, though -5 bytes if the output is the increasing sequence separated by + as shown above. If there exists no such sequence, then the number itself should be printed.

This is code golf. Standard rules apply. Shortest code in bytes wins.


Samples (note that formatting varies)

Input: 9
Output: 2,3,4
Input: 8
Output: 8
Input: 25
Output: [3,4,5,6,7]

Answer*

Draft saved
Draft discarded
Cancel
3
  • \$\begingroup\$ Technically this predicate is returning All solutions <N, even though it renders the longest one first. Are there any rules allowing this? \$\endgroup\$ Commented Sep 4, 2022 at 12:00
  • \$\begingroup\$ @Razetime An interesting question. The opposite, that it can unify with all possibilities, has been discussed and allowed, but I can't find any other discussion. It would only cost two bytes (,!) to modify it, but it might be worth opening a meta question on it \$\endgroup\$ Commented Sep 4, 2022 at 12:55
  • \$\begingroup\$ I'm not sure of the golf rules, but prolog does have once/1. \$\endgroup\$ Commented Sep 15, 2022 at 22:29

AltStyle によって変換されたページ (->オリジナル) /