# Triangular Dependencies

A triangular number is a number that is the sum of n natural numbers from 1 to n. For example 1 + 2 + 3 + 4 = 10 so 10 is a triangular number.

Given a positive integer (0 < n <= 10000) as input (can be taken as an integer, or as a string), return the smallest possible triangular number that can be added to the input to create another triangular number.

For example given input 26, adding 10 results in 36, which is also a triangular number. There are no triangular numbers smaller than 10 that can be added to 26 to create another triangular number, so 10 is the correct result in this case.

0 is a triangular number, therefore if the input is itself a triangular number, the output should be 0

## Testcases

Cases are given in the format input -> output (resulting triangular number)

0     -> 0   (0)
4     -> 6   (10)
5     -> 1   (6)
7     -> 3   (10)
8     -> 28  (36)
10    -> 0   (10)
24    -> 21  (45)
25    -> 3   (28)
26    -> 10  (36)
34    -> 21  (55)
10000 -> 153 (10153)


## Scoring

This is so fewest bytes in each language wins!

• Isn't it 26 -> 2?
– Okx
Jun 29 '17 at 10:29
• @Okx I made the same mistake, you need to find a triangular number to add to the current one to make another triangular number. Jun 29 '17 at 10:31
• Related. (borderline duplicate) Jun 29 '17 at 10:31

# Python 2, 82 bytes

f=lambda n,R=:n-sum(R)and f(n,[R+[R[-1]+1],R[1:]][sum(R)>n])or sum(range(R))


Try it online

This was created by modifying this answer from the related question.

• works not for 8192 Jun 29 '17 at 18:09
• It doesn't work for that on the related question either, because of the recursion depth. I'm not sure what the consensus is on that. Jun 29 '17 at 19:26
• Some other answers have the same problem. I give only the info Jun 29 '17 at 19:37

# Retina, 70 bytes

.+
$* 1+$&;$&; {^(1+);(?=(\b1|1\2)+;)\1(1*);1*$3
};(1*)$1$1;1\$1
1


Try it online! Link includes test suite. Explanation: The algorithm works with three numbers, the input number, the sum of the input number and the current triangular number, and the index of the current triangular number. If the sum is triangular (using @MartinEnder's excellent algorithm) then the whole thing is replaced by the difference of the sum and the original number, thus achieving the desired result. Otherwise, the index is incremented and added to the sum, until the sum becomes triangular. Note that if the input number is zero then all of this is simply ignored as the result is zero anyway.

## Swift 3.0,97 bytes

let n=4
var o=0,s=0.0;for i in 0...n{o=i*(i+1)/2;s=sqrt(Double(8*(n+o)+1))
if floor(s)==s{break}}


To see output use print(o)

Try it online!

# Ruby, 44 bytes

->n{*r=a=b=0;r<<a+=b+=1until r-[a-n]!=r;a-n}


Try it online!