Question: In python I need a function that takes an integer and returns the absolute value of n minus the nearest [triangle number](http://en.wikipedia.org/wiki/Triangular_number) to n. The way I'm doing it now is by generating a list of all the triangle numbers up to n. 
Then using:

```
def closest(myList, myNumber):
    c = min(myList, key=lambda x:abs(x-myNumber))

```

To find the closest triangle number. 

The end result list should look like:

```
[0, 0, 1 , 0 , 1 ,1 , 0 , 1, 2 , 1, 0 , 1, 2, 2, 1, 0, etc.]

```

If you have another method of generating the same result that's faster go for it.

Answer: 
In my solution I have used the fact that 
let K = sqrt(2\*N)
 if N is a triangular number then it will be Kth triangular number
We know Kth triangular number will be K\*(K+1)/2

Here is my solution in Python

```
from math import sqrt
from math import floor
def close_triangle(n):
m = floor(sqrt(2*n))
t1 = m*(m+1)/2       #next triangular number to n
m = m-1
t2 = m*(m+1)/2       #previous triangular number to n
diff1 = t1-n
diff2 = n - t2
if diff1 < diff2 :
  return t1
else:
  return t2
print "Nearest trianguler number";
print close_triangle(13)

```
I have one solution that doesn't need calculate every triangle number first, but I am not sure whether it's best.

As formula of triange number is

```
    A(n) = n*(n-1)/2       (n is integer)

```

For input x, it should be in middle of A(n) and A(n+1)

```
    A(n) <= x <= A(n+1)

```

For A(n) we have:

```
    n * (n - 1) / 2 <= x
    (n - 1)^2 < n * (n-1) <= 2*x
    n < sqrt(2*x) + 1

```

For A(n+1) we have:

```
    (n + 1)^2 > (n + 1) * n >= 2*x
    n > sqrt(2*x) - 1

```

Now, if we have input number x, we could rapidly find n that makes x in [A(n),A(n+1)], then we only need to calculate distance of [abs(A(n) - x),abs(A(n+1) - x)] and make smallar one as real output.