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

Return to Revisions

5 of 5
minor update
Arnauld
  • 205.5k
  • 21
  • 187
  • 670

##JavaScript (ES6), 52 bytes

f=(n,t=0)=>t<n?f(n-++t,t):t.toString(36)+(n?f(n):'')

###How?

Rather than explicitly computing Ti = 1 + 2 + 3 + ... + i, we start with t = 0 and iteratively subtract t + 1 from n while t < n, incrementing t at each iteration. When the condition is not fulfilled anymore, a total of Tt has been subtracted from n and the output is updated accordingly. We repeat the process until n = 0.

Below is a summary of all operations for n = 100.

 n | t | t < n | output
----+----+-------+--------
100 | 0 | yes | ""
 99 | 1 | yes | ""
 97 | 2 | yes | ""
 94 | 3 | yes | ""
 90 | 4 | yes | ""
 85 | 5 | yes | ""
 79 | 6 | yes | ""
 72 | 7 | yes | ""
 64 | 8 | yes | ""
 55 | 9 | yes | ""
 45 | 10 | yes | ""
 34 | 11 | yes | ""
 22 | 12 | yes | ""
 9 | 13 | no | "d"
----+----+-------+--------
 9 | 0 | yes | "d"
 8 | 1 | yes | "d"
 6 | 2 | yes | "d"
 3 | 3 | no | "d3"
----+----+-------+--------
 3 | 0 | yes | "d3"
 2 | 1 | yes | "d3"
 0 | 2 | no | "d32"

###Test cases

f=(n,t=0)=>t<n?f(n-++t,t):t.toString(36)+(n?f(n):'')
console.log(f(1)) // 1
console.log(f(2)) // 11
console.log(f(3)) // 2
console.log(f(4)) // 21
console.log(f(5)) // 211
console.log(f(6)) // 3
console.log(f(100)) // d32
console.log(f(230)) // k5211
console.log(f(435)) // t
console.log(f(665)) // z731

Arnauld
  • 205.5k
  • 21
  • 187
  • 670

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