[Question]
  [
**Let's count...** 
Count up to 2 and back to 1  
Count up to 4 and back to 1  
Count up to 6 and back to 1  
... ok you got it...
put all these together and you'll get the following sequence 
```
 {1,2,1,2,3,4,3,2,1,2,3,4,5,6,5,4,3,2,1,2,3,4,5,6,7,8,7,6,5,4,3,2,1,2,3...}
```
**Challenge**  
Given an integer `n>0`for 1-indexed (or `n>=0` for 0-indexed), output the nth term of this sequence 
**Test cases** 
```
Input->Output  
1->1  
68->6  
668->20  
6667->63  
10000->84
```
**Rules**
your program must be able to compute solutions up to n=10000 in under a minute
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
  
[Answer]
# JavaScript (ES7), ~~59 ... 44~~ 43 bytes
*Saved 1 byte thanks to Titus*
Expected input: 1-indexed.
```
n=>(n-=(r=(~-n/2)**.5|0)*r*2)<++r*2?n:r*4-n
```
Initially inspired by a formula for [A004738](http://oeis.org/A004738), which is a similar sequence. But I ended up rewriting it entirely.
### Test cases
```
let f=
n=>(n-=(r=(~-n/2)**.5|0)*r*2)<++r*2?n:r*4-n
console.log(f(1))     // -> 1
console.log(f(68))    // -> 6
console.log(f(668))   // -> 20
console.log(f(6667))  // -> 63
console.log(f(10000)) // -> 84
```
### How?
The sequence can be arranged as a triangle, with the left part in ascending order and the right part in descending order.
Below are the first 4 rows, containing the first 32 terms:
```
            1 | 2
        1 2 3 | 4 3 2
    1 2 3 4 5 | 6 5 4 3 2
1 2 3 4 5 6 7 | 8 7 6 5 4 3 2
```
Now, let's introduce some variables:
```
 row  | range   | ascending part              | descending part
 r    | x to y  | 1, 2, ..., i                | 4(r+1)-(i+1), 4(r+1)-(i+2), ...
------+---------+-----------------------------+-----------------------------------------
  0   |  1 -  2 |                           1 | 4-2
  1   |  3 -  8 |                   1   2   3 | 8-4  8-5  8-6
  2   |  9 - 18 |           1   2   3   4   5 | 12-6 12-7 12-8  12-9  12-10
  3   | 19 - 32 |   1   2   3   4   5   6   7 | 16-8 16-9 16-10 16-11 16-12 16-13 16-14
```
We start with 2 elements at the top and add 4 elements on each new row. Therefore, the number of elements on the 0-indexed row ***r*** can be expressed as:
```
a(r) = 4r + 2
```
The 1-indexed starting position ***x*** of the row ***r*** is given by the sum of all preceding terms in this arithmetic series plus one, which leads to:
```
x(r) = r * (2 + a(r - 1)) / 2 + 1
     = r * (2 + 4(r - 1) + 2) / 2 + 1
     = 2r² + 1
```
Reciprocally, given a 1-indexed position ***n*** in the sequence, the corresponding row can be found with:
```
r(n) = floor(sqrt((n - 1) / 2))
```
or as JS code:
```
r = (~-n / 2) ** 0.5 | 0
```
Once we know ***r(n)***, we subtract the starting position ***x(r)*** minus one from ***n***:
```
n -= r * r * 2
```
We compare ***n*** with ***a(r) / 2 + 1 = 2r + 2*** to figure out whether we are in the ascending part or in the descending part:
```
n < ++r * 2 ?
```
If this expression is true, we return ***n***. Otherwise, we return ***4(r + 1) - n***. But since ***r*** was already incremented in the last statement, this is simplified as:
```
n : r * 4 - n
```
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
```
(!!)$do k<-[1,3..];[1..k]++[k+1,k..2]
```
[Try it online!](https://tio.run/##BcFBCoAgEADAr6zgodAWrWP1ksWDUJKsmlT/32au@PJZikjaB6VGfdzA20TeLohhJY/IwRhi4y0jzkFqzA126E9uH2iosUMCcojeuSA/ "Haskell – Try It Online")
Zero-indexed. Generates the list and indexes into it. Thanks to Ørjan Johansen for saving 2 bytes!
---
# [Haskell](https://www.haskell.org/), 38 bytes
```
(!!)[min(k-r)r|k<-[0,4..],r<-[1..k-2]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P81WQ1FRMzo3M08jW7dIs6gm20Y32kDHRE8vVqcIyDTU08vWNYqN/Z@bmJmnYKtQUJSZV6KgopCbWKCQphBtoKdnaGAQ@x8A "Haskell – Try It Online")
Zero-indexed. Generates the list and indexes into it.
---
# [Haskell](https://www.haskell.org/), 39 bytes
```
n%k|n<k=1+min(k-n)n|j<-k+4=(n-k)%j
(%2)
```
[Try it online!](https://tio.run/##BcGxCoAgEADQva@4IUERRaNRvyQaHJL09JBq9N@v9@704tUaMwmcFDB63QtJNKRo1mBQ71GSQSXqkqMUm@KeCkGE8RT6YIWeBmQ4nLXeuZN/ "Haskell – Try It Online")
Zero-indexed. A recursive method.
[Answer]
# [Python](https://docs.python.org/2/), 46 bytes
```
f=lambda n,k=2:-~min(n,k-n)*(n<k)or f(n-k,k+4)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU8n29bISrcuNzNPA8jWzdPU0sizydbML1JI08jTzdbJ1jbR/M@VBuTnKWTmKUQbGgBBrIK2QlFiXnqqBpCraVVQlJlXAjRKQSmmREkHpFHzPwA "Python 2 – Try It Online")
Zero indexed.
[Answer]
## [Husk](https://github.com/barbuz/Husk), 8 bytes
```
!…ṁoe1DN
```
1-indexed.
[Try it online!](https://tio.run/##yygtzv7/X/FRw7KHOxvzUw1d/P7//29oAAQA "Husk – Try It Online")
## Explanation
```
!…ṁoe1DN  Implicit input (an integer).
       N  Positive integers: [1,2,3,4,...
  ṁo      Map and concatenate
      D   double: [2,4,6,8,...
    e1    then pair with 1: [1,2,1,4,1,6,1,8,...
 …        Fill gaps with ranges: [1,2,1,2,3,4,3,2,1,2,3,4,5,6,...
!         Index with input.
```
[Answer]
# [Perl 6](https://perl6.org), 29 bytes
```
{({|(1...$+=2...2)}...*)[$_]}
```
[Try it online](https://tio.run/##ZZFhT8IwEIa/91e8RLSrloVtMEiWyWd/gyKpW5HFseJaMAT57bNdgIk2uV7z3HvX63Uj6zJutlpiF/tZQtZ73GUql0ibg3f49gLf9/sPaWhdyI52v2fP/cX82GixB10WtTaIxqAcbdZrNE5IG6In/6RRGJiVhBZrCaHbc7YSZSmrdzk7p3o2lUF@7uAFPOTOIj6y1p3HPLb2n0341NqfGMPM1t5LTdHrgVaKdo0RvX1DXuhNaYGH/gIMBwK4uL9cG4/eTnIMEFDGQZGmj5curdZyRo6EnAsEcCvBDYILi6dnFneshY6Fw18wnpyEEXHTf9FG1GZgCjusFJX6SrqLhnY56XTUKmWVX@mu5u6GrtSHa/yiG6Ar7h6mZaaqXGOpavsrwqAU9jtVJWnzAw "Perl 6 – Try It Online")
0-based
## Expanded:
```
{  # bare block lambda with implicit parameter ｢$_｣
  (
    # generate an outer sequence
    {           # bare block lambda
      |(        # flatten into outer sequence
        # generate an inner sequence
        1       # start at 1
        ...     # go (upward) towards:
        $       # an anonymous state variable (new one for each outer sequence)
          += 2  # increment by 2
        ...     # go (downward) towards:
        2       # stop at 2 (1 will come from the next inner sequence)
      )
    }
    ...         # keep generating the outer sequence until:
    *           # never stop
  )[ $_ ]       # index into outer sequence
}
```
The inner sequence `1...$+=2...2` produces
```
(1, 2).Seq
(1, 2, 3, 4, 3, 2).Seq
(1, 2, 3, 4, 5, 6, 5, 4, 3, 2).Seq
(1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2).Seq
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2).Seq
...
```
To get it to be 1-based, add `0,` before the second `{`, or add `-1` after `$_`
[Answer]
# R, 64 bytes
```
function(n)unlist(sapply(seq(2,n,2),function(x)c(2:x-1,x:2)))[n]
```
Function that takes an argument `n`. It creates a vector `2:n` with increments of 2. For each of these, the vector `1:(x-1)` and `x:2` is created. This in total will be longer than `n`. We `unlist` it, to get a vector and take the `n`-th entry.
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
def f(x):n=int((x/2)**.5);print 2*n-abs(2*n*n+2*n+1-x)+2
```
[Try it online!](https://tio.run/##JYw7DoAgEAV7TrGx2gU/SGKj8SY2GkWlWA1S4OmRxOZNMsm8@w3HxSaldbNgMVLP48kBMTaGpKw7Gm6fBRjJ1bw8mClZ5VVtFUmZZC8PDk4GP/O@Yas19QL@yJVQTKEoRb52lD4 "Python 2 – Try It Online")
This is 0-indexed.
*-1 byte thanks to @JustinMariner*
**How this Works**
We note that the 1-indexed `n`-th group (`1, 2, ... 2n ..., 2, 1`) occurs from elements numbered 0-indexed `2(n-1)^2` to `2n^2`.
To find the element at index `x`, we can find the group number `n` that `x` is in. From that, we calculate the distance from the center of the group that `x` is. (This distance is `abs(2*n**2+2*n+2-x)`). 
However, since the elements *decrease* further away from the center of a group, we subtract the distance from the maximum value of the group.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
### Code:
```
ÅÈ€1Ÿ¦¹è
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//cOvhjkdNawyP7ji07NDOwyv@/7cEgv@6JQA "05AB1E – Try It Online")
### Explanation:
```
ÅÈ           # Get all even numbers until input (0, 2, ..., input)
  €1         # Insert 1 after each element
    Ÿ        # Inclusive range (e.g. [1, 4, 1] -> [1, 2, 3, 4, 3, 2, 1])
     ¦       # Remove the first element
      ¹è     # Retrieve the element at the input index
```
[Answer]
# JavaScript, 39 bytes
```
f=(n,t=2)=>n>t?f(n-t,t+4):n>t/2?t-n+2:n
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~, 9 bytes
```
ḤŒḄṖµ€Fị@
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef//4bikxZLhuIThuZbCteKCrEbhu4tA////Njg "Jelly – Try It Online")
Also 1 indexed, and finishes pretty fast.
One byte saved thanks to @ErikTheOutgolfer!
Explanation:
Hypothetically, let's say the input (`a`) is 3.
```
    µ€      # (Implicit) On each number in range(a):
            #
Ḥ           # Double
            #   [2, 4, 6]
            #
 ŒḄ         # Convert to a range, and Bounce
            #   [[1, 2, 1], [1, 2, 3, 4, 3, 2, 1], [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]]
            #
   Ṗ        # Pop
            #   [[1, 2], [1, 2, 3, 4, 3, 2], [1, 2, 3, 4, 5, 6, 5, 4, 3, 2]]
            #
     F      # Flatten
            #   [1, 2, 1, 2, 3, 4, 3, 2, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2]
            #
      ị@    # Grab the item[a]
            #   1
            #
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
li:"@EZv4L)]vG)
```
1-based.
[**Try it online!**](https://tio.run/##y00syfn/PyfTSsnBNarMxEcztsxd8/9/MzMLAA "MATL – Try It Online")
This times out for the largest test cases in TIO, but finishes in time on my desktop computer (compiler running on MATLAB R2017a). To display elapsed time, add `Z`` at the end of the code.
```
>> matl 'li:"@EZv4L)]vG)Z`'
> 10000
84
15.8235379852476
```
### Explanation
The code generates many more terms than necessary. Specifically, it computes `n` "pieces" of the sequence, where each piece is a count up and back to 1.
```
l       % Push 1
i       % Push input, n
:       % Range [1 2 ...n]
"       % For each k in that range
  @E    %   Push 2*k
  Zv    %   Symmetric range: [1 2 ... 2*k-1 2*k 2*k-1 ... 2 1]
  4L)   %   Remove last entry: [1 2 ... 2*k-1 2*k 2*k-1 ... 2]
]       % End
v       % Concatenate all stack contents into a column vector
G)      % Get n-th entry. Implicitly display
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~12~~ 10 bytes
```
!ṁ§¤+hḣṫİ0
```
[Try it online!](https://tio.run/##yygtzv7/X/HhzsZDyw8t0c54uGPxw52rj2ww@P//v6EBEAAA "Husk – Try It Online")
1-indexed, works quite fast
### Explanation
```
!ṁ§¤+hḣṫİ0
 ṁ      İ0    Map the following function over the even numbers and concatenate the results together
  §   ḣṫ      Get the ranges 1-n and n-1, then... 
   ¤+h         remove the last element from both of them and concatenate them together
!             Return the element of the resulting list at the given index
```
[Answer]
# Mathematica, 90 bytes
```
Flatten[{1}~Join~Table[Join[Rest[p=Range@i],Reverse@Most@p],{i,2,Round[2Sqrt@#],2}]][[#]]&
```
[Try it online!](https://tio.run/##FcaxCsIwEADQXxEKTjfY7IWbHARBottxQ9SrHtSkTU6X0v561De9V7Cn3krtu7ofgplEmttlPSSN6yVcB6F/yUsxGjsf4kNQGbx8JBfBYyqGI8Os4MCnd7yTO0/ZsGFwCzNRw7ytp6zRNthTu/vhWr8 "Mathics – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 62 bytes
```
.+
$*
^((^.|\2..)*)\1.
6$*1$2$2;1
(?=.+;(.+))\1(.+).*;\2.*
$.2
```
[Try it online!](https://tio.run/##HYoxCoAwEAT7e8cJlwssXoooBLH0EyFoYWFjIZb@PUYXhilmr/0@zq12sqwVnlipiBQ8OQBOXTZQZDUOHJKRzBN8EnjXyidoak8lRqjVKI4Uf@JA1re9 "Retina – Try It Online") Link includes test cases. Input is 1-indexed. The first stage is just decimal to unary conversion. The second stage finds the highest square number `s` strictly less than half of `n`; `$1` is `s²`, while `$2` is `2s-1`. It calculates two values, first the number of numbers in the current up/down run, which is `4(s+1) = 4s+4 = 2$2+6`, and secondly the position within that run, which is `n-2s² = n-(2$1+1)+1 = n-$&+1`, which just requires a `1` to make up for the `1` used to enforce the strict inequality. The final stage then counts from that position to both the start and end of the run and takes the lower result and converts it to decimal.
[Answer]
# Mathematica, 67 bytes
```
(t=z=1;While[(x=3-4t+2t^2)<#,t++;z=x];If[#-z>2t-2,4t-5+z-#,#-z+1])&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvtfo8S2ytbQOjwjMyc1WqPC1ljXpETbqCTOSNNGWadEW9u6yrYi1tozLVpZt8rOqETXSMekRNdUu0pXWQcoom0Yq6n2P6AoM69EwSEt2tAACGL//wcA "Mathics – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 43 + 1 (-p) = 44 bytes
```
$_=($n=2*int sqrt$_/2)+2-abs$n/2*$n+$n+1-$_
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lZDJc/WSCszr0ShuLCoRCVe30hT20g3MalYJU/fSEslTxuIDHVV4v//twSCf/kFJZn5ecX/dX1N9QwMDf7rFgAA "Perl 5 – Try It Online")
I was working on a formula to calculate the n-th element directly. 
 Then I saw that @fireflame241 had done that work, and I golfed it into Perl.
~~# [Perl 5](https://www.perl.org/), 50 + 1 (-n) = 51 bytes~~
```
push@r,1..++$",reverse 2..++$"while@r<$_;say$r[$_]
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gtDjDoUjHUE9PW1tFSacotSy1qDhVwQjCL8/IzEl1KLJRibcuTqxUKYpWiY/9/98SCP7lF5Rk5ucV/9f1NdUzMDT4r5sHAA "Perl 5 – Try It Online")
Results are 0 indexed.
[Answer]
# [Haskell](https://www.haskell.org/), ~~115~~ 81 bytes
```
y%x=snd(span(<x)$scanl(+)y[y+1,y+3..])!!0
g 1=1
g x|1%x>2%x=1+g(x-1)|1>0=g(x-1)-1
```
[Try it online!](https://tio.run/##JcuxCsMgFEDRvV@RQAI@bMSXrjVTx/xByPBoi5WqleigkH83gS6Xs9wPxe/b2mpc@G2peVAiMZuYaumziv7FYiDP7hm6@CRvGYeyFI7Xwm9CrNC28qIbVHg279jnaTw/5JrlAWHHSao/B6yOjFdhMz51jgLTsKAQo1zrAQ "Haskell – Try It Online")
There is some magic going on here. Could probably be shorter if I used a normal approach though.
## Explanation
First we define `%`. `%` is a function that takes two variables `x`, and `y`. It constructs a list `scanl(+)y[y+1,y+3..]` and finds the first element of that list greater than `x`. `scanl(+)` just performs iterative sums, to get the triangular numbers we would do `scanl(+)0[1..]`, to get the square numbers we would do `scanl(+)0[1,3..]`. The two lists in particular we will be constructing are `scanl(+)2[3,5..]` and `scanl(+)1[2,4..]` these are the inflection points of the pattern.
Now we define the main function `g` which takes an `x`. If `x` is one we return `1` because that's the first value. Otherwise we check the next two inflection points, if the down inflection is larger `1%x>2x` we return the successor of `g$x-1` otherwise we return the predecessor of `g$x-1`.
## Ok but why does that work?
First of all "Whats with the way we find vertices?". Its important to note the distance between consecutive vertices of the same type. You will notice that the differences are growing by 2 each time. This makes sense because the triangles bases become wider by 2 each time. We can make a list constant difference using a list literal like so `[2,4..]` and we use `scanl(+)` to to turn these lists into our vertex lists, based on the location of the first vertex and the first difference.
So now that we have a way of finding upward and downward vertices we can use that information to get the values. We say that the first value is `1` otherwise we have to take either the successor or the predecessor. If the next vertex is a upward one we want to take the predecessor, otherwise we take the successor.
# [Haskell](https://www.haskell.org/), ~~56~~ ~~51~~ 46 bytes
Here's my better solution with less math and fewer bytes.
```
d x|e<-[1..x-1]=e++map(x+1-)e
(([1..]>>=d)!!0)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0WhoibVRjfaUE@vQtcw1jZVWzs3sUCjQttQVzOVK90WJBFrZ2eb8j83MTPPtqAoM69EBaQiXVFRM9pAT8/QIPY/AA "Haskell – Try It Online")
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 14 bytes
```
SF}SDtO_+)sQt@
```
[Try it here!](http://pyke.catbus.co.uk/?code=SF%7DSDtO_%2B%29sQt%40&input=10)
```
S              -    range(1, input)
 F}SDtO_+)     -   for i in ^:
  }            -      ^ * 2
   S           -     range(1, ^)
        +      -    ^ + v
     tO_       -     ^[1:-1:-1]
          s    -  sum(^)
           Qt@ - ^[input-1]
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 120 bytes
Explanation:
 pretty simple, the first nested loop climbs up to our max, the second climbs back down to 2. The repeat for each multiple of 2.
```
x=>{var a=0;for(int i=2,j=0;j<x;i+=2){for(var b=1;b<=i&j<x;b++,j++){a=b;}for(var c=i-1;c>1&j<x;c--,j++){a=c;}}return a;}
```
[Try it online!](https://tio.run/##hc49a8MwEAbguf4VIpRiY6tEGZyALC2BTu3UoUPpIKtyOJNKQZJDitBvd2W33kpycHAfz/BKh6Wxahwc6AN6/XZefdFMHoVz6BQy54UHiZ4GLRvQvkrNOzZeGA9nYZFga9oZm6czArap@rT3zYVCyTZFmD6TahmhbcPgYXq1ZVn1ZVkEwVoaFyIZYEIlJ7ORGC9G0hit8oPVSNA40iXR2cAnehGgc@dtiv7@gYQ9uCJkd3ujnTmqxzcLXj2DVvn9iiDMUehyUsRVQf839Q7zROrdNbOgG6re/rF6e8WRdaoZztOvjFkcfwA "C# (.NET Core) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~78~~ 75 bytes
*Saved 1 byte thanks to Step Hen*
*Saved 1 byte thanks to Mr. Xcoder*
```
->n{a=0;b=2;c=1;n.times{if a==b then c=0;b+=2;end;c=1if a<2;a+=c<1?-1:1};a}
```
[Try it online!](https://tio.run/##XY5BDoMgFET3nuLv0FiJuCzSHsV8KU1tAE3BRYOcnWLThelu8uZlMq91fKek0YCA5mIDipaPouNSMG6pn4xyYboDCjGCfygLchfqbCh726297DuOtZA9uzbszCLHmLxyfphXv6w@L5NAiiPpeygZpaxtK@rnAanBBQJsSiujrN8gH6IStS5/5Ks5iPQ5T7YkJyDV/yCJpMjRwYGnDw "Ruby – Try It Online")
Hopefully I can get some tips for pulling the bytecount down more. I tried to take a simple approach.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 53 bytes
```
n->{int i=2;for(;n>i;i+=4)n-=i;return n>i/2?i-n+2:n;}
```
[Try it online!](https://tio.run/##jVFtS8MwEP7c/Ip8TFkbWZ0vLHYyREFwfpmKICKxTbvM9lLSdDrGfntNuzqHUxBy5O655567S@Z8wX1VCJjHb7XMC6UNnluMVkZmdKw1X5YM7SWSCiIjFdCrzvmFUxoteE6vwUxbjyFUVK@ZjHCU8bLEEy4BrZDTgaXhxl4LJWOc2xSxVRLSp2fMdVq6yLFUxx4JxmIRDjGId7yJVn0v8Bo79AbWvv0j79jaPnbinVrb5tbMCk@XpRE5VZWhhe1sMiCb/alRm1nIdheqOaTiIlOliEnfwxHNBKRm5tKcF6TZbDhMJMS3ZnYndO5aiVaLuK77z17Rn8wd4WYikQpNJ@PHl4fxzf1lW7VGzs93taV4t7CJ4aN71q9fPOvkPNw5I5zgsAZ/tGr4MgxYojRhMJJM9sKBC34omRam0oAteBCcSx96wRDYum6m71IJ5UWRLYlt2E63RvUn "Java (OpenJDK 8) – Try It Online")
*-2 bytes thanks to Nevay.*
1-indexed.
**TL;DR** We split the sequence into convenient chunks, find the chunk `n` is in, then find the `nth` position in the chunk.
Here, we can split the sequence like `[[1,2],[1,2,3,4,3,2],[1,2,3,4,5,6,5,4,3,2],...]`, which gives us chunk sizes of `4i-2`. Starting with `i=2`, we subtract `i` from `n`, essentially moving upwards a chunk at a time. Once we satisfy `n<=i`, we know `n` is now the position of the correct value in the current chunk.
We then get the value by comparing `n` to `i`, the size of the chunk. The midpoint of each chunk is equal to `i/2+1`; if `n` is less than this, we simply return `n`. If `n` is greater, we return `i-n+2`.
# Example
```
n = 16, i = 2
Is n > i? Yes, n = n - 2 = 14, i = i + 4 = 6
Is n > i? Yes, n = n - 6 = 8, i = i + 4 = 10
Is n > i? No, stop looping.
10 / 2 + 1 = 6
Is n > 6? Yes, return i - n + 2 = 8 - 6 + 2 = 4
```
[Answer]
# [Python 2](https://docs.python.org/2/), 5! bytes (120 bytes :P)
```
r=range
a=[]
for i in r(2,998,2): 
	for j in r(1,i+1): a.append(j)
	for j in r(i-1,1,-1): a.append(j)
print a[input()-1]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPZUr0TY6listv0ghUyEzT6FIw0jH0tJCx0jTSoGLEyScBRE21MnUNgQKJuolFhSk5qVoZGmiyGfqGuoY6uiiKykoyswrUUiMzswrKC3R0NQ1jP3/HwA "Python 2 – Try It Online")
Straightforward, makes the list and then takes input'th element 
[Answer]
# [Python 3](https://docs.python.org/3/), 184 156 bytes
```
l,n,r=list,next,range
h=lambda x:l(r(1,x))+l(r(x-2,1,-1))
def g():
	x=3
	while True:yield from h(x);x+=2
def f(i):
	x=g()
	for _ in r(i-1):n(x)
	return n(x)
```
[Try it online!](https://tio.run/##JY7dCsIwDIWv16fInQ1GWRVUJvUpvJfJOlfoOokVK2PPPlsXyB985yTPb@gGv59nR55YO/sK5E0MxLV/GNFpV/f3poZYOclSUURc5yludqRooxBFY1p4SKxEEfVeFJ/OOgNXfpvqa41roOWhh05GPMe13v3xVtqFTzpRtAPDDawHljY5Vj6xomAT3uwhL3MmgnmFDKUn4HBKuZTDkUCVKSg7Ptn6IFdjOYG@wKim1TZp@zrILKd0OHdEnH8 "Python 3 – Try It Online")
golfed with Python generator for "lazy" evaluation
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 47 bytes
```
g=q{p=p+1~p=:|_Xg\g=g+q~g=1or g>=r|r=r+1┘q=q*-1
```
## Explanation
```
g=q         var g is the current value of the sequence; set to 1 at the start
{           DO infinitely
p=p+1       raise the step counter (var p)
~p=:|_Xg    IF p equals the input term a (read from cmd line) THEN QUIT, printing g
\           ELSE
g=g+q       raise (or decrement) g by q (q is 1 at the start of QBIC)
~g=1        IF g is at the lower bound of a subsequence
    or g>=r OR g is at the upper bound (r start as 2 in QBIC)
|r=r+1      THEN increment r (this happens once on lower bound, and once on upper, 
            total of 2 raise per subsequence)
┘q=q*-1     and switch q from 1 to -1
```
[Answer]
# [Röda](https://github.com/fergusq/roda), 54 bytes
```
f n{seq 1,n|{|i|seq 1,2*i;seq 2*i-1,2}_|head n+2|tail}
```
[Try it online!](https://tio.run/##JYjBCsIwGIPP3VPk4KHTCXaHKYhPIrIV2rIftJ1dPci6Z6@/LJDkS2IwuhQHv8z2DdX4vGTKG7d7uv6J@8hr7fNotYE/tDlpeq7lpcljqYQLEQTmu2rQXdhbdOcG6sR6wIRKiOkzj3LYEW4Yat4pfuEk1ciYIvkke35N8LZayw8 "Röda – Try It Online")
Call with: `try f(n)`
This function returns quickly the answer, but *after* that does some unnecessary calculations and eventually runs out of memory.
As the function does return the actual answer shortly after it is called (clearly under a minute), I think this answer is valid.
(In Röda functions can return values before they exit due to parallelism.)
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform),99 95 86 bytes
```
n=>{int i=1,t=2,d=0;for(;n>1;){i+=1-2*d;if(i==t){d++;t+=2;}if(i==1)d--;n--;}return i;}
```
[Try it online!](https://tio.run/##fcoxSwQxEAXg2vyKlIm7K5ctzoMx2xxYaWVhIRZLklsGzgmXzAoS8tvXiK3nwIPH@8blwcUUtjUjLfLlK3P4AOHOc87yUkTmmdHJz4hePs9IKnNqj2/vck5L1kU8ruQekLhvmRa7kZ1KqxKt6dmOvbc7OMWkgCYDumBnzTDeesCTQmtZF991wJ0dof5ORvthAGqpKfCaSCLUDYS4OUbK8RzuXhNyeEIKalFGa/hb9ofr9K/t76@i2bX70Srq9g0 "C# (.NET Core) – Try It Online")
Lambda function that takes and returns an integer. Single loop that handles counting up and down.
[Answer]
# PHP, 65+1 bytes
```
for($x=$d=$z=1;--$argn;)$d=($x+=$d)>1?$x>$z?-1:$d:!!$z+=2;echo$x;
```
Run as pipe with `-R` or [try it online](http://sandbox.onlinephpfunctions.com/code/778690bea522f241f2e93c5c31c4c758c55d48e3) (or uncomment one of the other versions).
A port of [tsh´s recursive JavaScript](https://codegolf.stackexchange.com/a/140160/55735) takes 66 bytes:
```
function f($n,$t=2){return$t<2*$n?$t<$n?f($n-$t,$t+4):$t-$n+2:$n;}
```
A port of [Arnauld´s solution](https://codegolf.stackexchange.com/a/140133/55735) takes 62+1:
```
$n=$argn;echo($n-=($r=(~-$n/2)**.5|0)*$r*2)<++$r*2?$n:$r*4-$n;
```
A golfed port of [Xanderhall´s Java](https://codegolf.stackexchange.com/a/140193/55735) has the shortest code so far (55+1 bytes):
```
for($n=$argn;$n+2>$i+=4;)$n-=$i-2;echo$n*2>$i?$i-$n:$n;
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~19~~ 18 bytes
```
-yhKs@/Q2 2a*yKhKt
```
**[Try it here!](https://pyth.herokuapp.com/?code=-yhKs%40%2FQ2+2a%2ayKhKt&test_suite=1&test_suite_input=0%0A67%0A667%0A6666%0A9999&debug=0)**
]