f=lambda n,k=1:(8*n+1)**.5%1and f(n+k,k+1)+k
Thanks to @xnor for a suggestion that saved 16 bytes!
Try it online!
Background
Let n be a non-negative integer. If n is the kth triangular number, we have
which means there will be a natural solution if and only if 1 + 8n is an odd, perfect square. Clearly, checking the parity of 1 + 8n is not required.
How it works
The recursive function n accepts a single, non-negative integer as argument. When called with a single argument, k defaults to 1.
First, (8*n+1)**.5%1
tests if n is a triangular number: if (and only if) it is, (8*n+1)**.5
will yield an integer, so the residue from the division by 1 will yield 0.
If the modulus is 0, the and
condition will fail, causing f to return 0. If this happens in the initial call to f, note that this is the correct output since n is already triangular.
If the modulus is positive, the and
condition holds and f(n+k,k+1)+k
gets executed. This calls f again, incrementing n by k and k by 1, then adds k to the result.
When f(n0, k0) finally returns 0, we back out of the recursion. The first argument in the first call was n, the second one n + 1, the third one n + 1 + 2, until finally n0 = n + 1 + … k0-1. Note that n0 - n is a triangular number.
Likewise, all these integers will be added to the innermost return value (0), so the result of the intial call f(n) is n0 - n, as desired.
26 -> 2
않습니까?