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*

Decompose a number into triangles

Given an integer n, decompose it into a sum of maximal triangular numbers (where Tm represents the mth triangular number, or the sum of the integers from 1 to m) as follows:

  • while n> 0,

    • find the largest possible triangular number Tm such that Tm ≤ n.

    • append m to the triangular-decomposition representation of n.

    • subtract Tm from n.

For example, an input of 44 would yield an output of 8311, because:

  • 1+たす2+たす3+たす4+たす5+たす6+たす7+たす8 = 36 < 44, but 1+たす2+たす3+たす4+たす5+たす6+たす7+たす8+たす9 = 45> 44.

    • the first digit is 8; subtract 36 from 44 to get 8 left over.
  • 1+2+3 = 6 < 8, but 1+2+3+4 = 10> 8.

    • the second digit is 3; subtract 6 from 8 to get 2 left over.
  • 1 < 2, but 1+2 = 3> 2.

    • the third and fourth digits must be 1 and 1.

Use the digits 1 through 9 to represent the first 9 triangular numbers, then use the letters a through z (can be capitalized or lowercase) to represent the 10th through 35th triangular number. You will never be given an input that will necessitate the use of a larger "digit".

The bounds on the input are 1 ≤ n < 666, and it will always be an integer.

All possible inputs and outputs, and some selected test cases (listed as input, then output):

1 1
2 11
3 2
4 21
5 211
6 3
100 d32
230 k5211
435 t
665 z731

An output of for an input of -1/12 is not required. :)

Answer*

Draft saved
Draft discarded
Cancel
3
  • 1
    \$\begingroup\$ I had f=(n,t=0)=>n?t+1>n?t.toString(36)+f(n):f(n-++t,t):1 \$\endgroup\$ Commented May 2, 2017 at 0:37
  • \$\begingroup\$ @Arnauld Oh wow, that's way better. You should post it yourself... \$\endgroup\$ Commented May 2, 2017 at 0:39
  • 1
    \$\begingroup\$ Alright. In your version, would it be safe to do f=(n,p=q=0) and f(n,++q+p)? \$\endgroup\$ Commented May 2, 2017 at 0:58

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