g | x | w | all
Bytes Lang Time Link
258jBasher2250909T150136Zmadeforl
018YASEPL250903T134302Zmadeforl
014Uiua250704T014813ZErikDaPa
026Perl 5 p250703T145218ZXcali
016TIBASIC TI83 Plus250703T140943Zmadeforl
007Vyxal 3250703T115541ZThemooni
026JavaScript ES7170428T003420ZArnauld
011Japt230103T173235ZShaggy
019J230103T161402ZConor O&
023Julia 1.0230102T023539ZDialFros
032Python 3230102T023028ZDialFros
008Vyxal230102T030639ZnaffetS
012Pyt171226T023812Zmudkip20
031Haskell171226T044514ZWheat Wi
078tinylisp171226T053615ZDLosc
006Husk171226T040416Zბიმო
025J170507T183431Zljeabmre
027APL Dyalog170507T135142Zuser4180
044C#170428T153140Zaloisdg
035PHP170428T135236ZJör
070Batch170428T134917ZNeil
007Jelly170428T002301ZDennis
00905AB1E170428T113143ZEmigna
027Alice170428T104712ZMartin E
03005AB1E170428T020438ZEduardo
068Octave170428T005606ZLuis Men
048C gcc170428T005828ZConor O&
008Jelly170428T004241ZLuis Men
011MATL170428T002710ZLuis Men

jBasher2, 258 bytes

create d with type number
divide 1 by 2
set that to d
create n with type number
ask for input
set that to n
multiply n by 2
get the square root of that
add that by d
parse that as int
set that to d
multiply d by d
subtract that by n
add that by 1
output that

fun!

YASEPL, 18 bytes

=n'=a$n*&+.5(^-n+<

explanation:

=n'=a$n*&+.5(^-n+<        packed
=n'                       get user input (n)
   =a$n                   create (a), set it to (n)  (which will be outputted)
       *                  times it by 2
        &                 square root it
         +.5(             round to nearest int
             ^            square it
              -n          subtract n
                +         add 1
                 <        finally, print

this is a translation of my ti-basic answer

Uiua, 14 bytes

+⊓˙׬⌊+0.5√⊸˙+

Uses the formula in Arnauld's answer.

Explanation:

+⊓˙׬⌊+0.5√⊸˙+
           ⊸˙+ => 2n
          √    => sqrt
      +0.5     => + 1/2
     ⌊         => floor
  ˙×           => sqr
+⊓  ¬          => + 1 - n

Try this online!

Perl 5 -p, 26 bytes

$_=(0|.5+sqrt$_*2)**2-$_+1

Try it online!

TI-BASIC (TI-83 Plus), 16 bytes

Input N
round(√(2N),0)²-N+1

hooray!

Vyxal 3, 7 bytes

d√◌²?‹-

Vyxal It Online!

d√◌²?‹-­⁡​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‏​⁢⁠⁡‌⁤​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌­
  ◌      # ‎⁡round(                   )
 √       # ‎⁢      sqrt(             )
# ‎⁣                    implicit n
d        # ‎⁤                      *2
   ²     # ‎⁢⁡squared
    ?‹-  # ‎⁢⁢-(n-1)
💎

Created with the help of Luminespire.

<script type="vyxal3">
d√◌²?‹-
</script>
<script>
    args=[["1"],["2"],["3"],["4"],["14"],["990"],["991"],["1000"],["1035"],["1036"],["12345"]]
</script>
<script src="https://themoonisacheese.github.io/snippeterpreter/snippet.js" type="module"/>

JavaScript (ES7), 26 bytes

n=>((2*n)**.5+.5|0)**2-n+1

Try it online!

An implementation of the following formula from OEIS:

$$a(n)=\lfloor\sqrt{2n}+1/2\rfloor^2-n+1$$

Japt, 11 bytes

0-indexed

gUòò@T±1ÃcÔ

Try it

gUòò@T±1ÃcÔ     :Implicit input of integer U
g               :Index into
 Uò             :  Range [0,U]
   ò            :  Range [0,each]
    @           :  Map each subrange
     T±1        :    Increment T (initially 0) by 1
        Ã       :  End map
         c      :  Flat map
          Ô     :    Reverse

J, 19 bytes

1-]-0.5*:@<.@+%:@+:

Try it online! Uses the formula from Arnauld's answer.

1-]-0.5*:@<.@+%:@+:
                 +:    2n
              %:@      sqrt(^)
    0.5      +         0.5 + ^
          <.@          floor(^)
       *:@             square(^)
  ]-                   input - ^
1-                     1 - ^
                       (computes - input + 1 in a golfier way)

J, 43 bytes

1+;@((#{.[:;(1<@,#&0)"0)<@|.;.1>:)@i.@+:i.]

Try it online!

Shortest non-formula solution I could think of. The array form of ;. is really unwieldly for code golf, and it doesn't help that ragged lists aren't that golfy either.

1+;@((#{.[:;(1<@,#&0)"0)<@|.;.1>:)@i.@+:i.]
                                  @i.@+:      range [0, 2n)
    (                       ;.1>:)            segment [1, 2n] according to
     (                 )                      the indices of triangular numbers:
            (       )"0                         over each integer in [0, 2n):
                 #&0                            create that many 0s
             1  ,                               prepend a 1 (a cut location)
              <@                                and box it
         [:;                                    then raze that boxed list
      #{.                                       and take 2n entries from that array
                        <@|.                  box and reverse each segment
  ;@                                          raze this list
                                        i.]   get the 0-based index of the input in it
1+                                            and add 1

For generating the indices of triangular number, the invariance under inverse transform (=(-:@*>:)@<.@%:@+:) is 1 byte longer, but much faster.

Julia 1.0, 29 23 bytes

!n=round((2n)^.5)^2-n+1

Try it online!

Port of Arnauld's JS answer.

-6 thx to @steffan

Python 3, 37 35 32 bytes

lambda n:round((2*n)**.5)**2-n+1

Try it online!

Port of Arnauld's JS answer.

-3 thx to @Steffan

Vyxal, 8 bytes

dɾ:ẇRfJi

Try it Online!

Pyt, 13 12 bytes

←Đ2*√½+⌊²-~⁺

Port of Arnauld's approach

Haskell, 31 bytes

r=round
f n=r(sqrt$2*n)^2-r n+1

Try it online!

This answer just uses the formula. It is the least interesting answer here, but it also happens to be the golfiest.

Haskell, 38 36 34 bytes

x!y|x<=y=1-x|v<-y+1=v+(x-y)!v
(!0)

Try it online!

(!0) is the point free function we are concerned with.

Explanation

Let me start out by saying I'm very happy with this answer.

The basic idea here is that if we remove the largest triangular number smaller than our input we can reverse it and add the triangular number back. So we define an operator !, ! takes our regular input, x, but it also takes an extra number y. y keeps track of the size of the growing triangular number. If x>y we want to recurse, we decrease x by y and increase y by one. So we calculate (x-y)!(y+1) and add y+1 to it. If x<=y we have reached our base case, to reverse x's placement in the row of the triangle we return 1-x.

Haskell, 54 bytes

f x|u<-div(x^2-x)2=[u+x,u+x-1..u+1]
(!!)$0:(>>=)[1..]f

Try it online!

(!!)$0:(>>=)[1..]f is a point-free function

Explanation

The first thing we are concerned with is f, f is a function that takes x and returns the xth row of th triangle in reverse. It does this by first calculating the x-1nd triangular number and assigning it to u. u<-div(x^2-x)2. We then return the list [u+x,u+x-1..u+1]. u+x is the xth triangular number and the first number on the row, u+x-1 is one less than that and the second number on the row u+1 is one more than the last triangular number and thus the last number on the row.

Once we have f we form a list (>>=)[1..]f, which is a flattening of the triangle. We add zero to the front with 0: so that our answers will not be offset by one, and supply it to our indexing function (!!).

Haskell, 56 bytes

f 0=[0]
f x|u<-f(x-1)!!0=[u+x,u+x-1..u+1]
(!!)$[0..]>>=f

Try it online!

This one is 2 bytes longer but a bit more elegant in my opinion.

tinylisp, 78 bytes

(d _(q((R N T)(i(l T N)(_(a R 1)N(a T R))(a 2(a T(s T(a N R
(d f(q((N)(_ 2 N 1

Defines a function f that performs the mapping. Try it online!

Ungolfed

We find the smallest triangular number that is greater than or equal to the input number, as well as which row of the triangle our number is in. From these, we can calculate the flipped version of the number.

The main function flip simply calls the helper function _flip starting from the top row.

(load library)

(def _flip
 (lambda (Num Row Triangular)
  (if (less? Triangular Num)
   (_flip Num (inc Row) (+ Triangular Row))
   (+ 2
    (- Triangular Num)
    (- Triangular Row))))))

(def flip
 (lambda (Num) (_flip Num 2 1)))

Husk, 6 bytes

!ṁ↔´CN

Try it online!

Explanation

!ṁ↔´CN  -- implicit input N, for example: 4
   ´ N  -- duplicate the natural numbers:
           [1,2,3,…] [1,2,3,…]
    C   -- cut the second argument into sizes of the first:
           [[1],[2,3],[4,5,6],[7,8,9,10],…]
 ṁ↔     -- map reverse and flatten:
           [1,3,2,6,5,4,10,9,8,7,15,…
!       -- index into that list:
           6

J, 25 bytes

3 :'>:y-~*:>.-:<:%:>:8*y'

As an explanation, consider f(n) = n(n+1)/2. f(r), given the row r, returns the leftmost number of the the rth row of the mirrored triangle. Now, consider g(n) = ceiling[f⁻¹(n)]. g(i), given the index i, returns the row on which index i is found. Then, f(g(n)) returns the leftmost number of the row on which index n is found. So, h(n) = f(g(n)) - (n - f(g(n)-1)) + 1 is the answer to the above problem.

Simplifying, we get h(n) = [g(n)]² - n + 1 = ceiling[(-1 + sqrt(1 + 8n))/2]² - n + 1.

From the looks of @Arnauld's formula, it appears that:

ceiling[(-1 + sqrt(1 + 8n))/2] = floor[1/2 + sqrt(2n)].

APL (Dyalog), 27 bytes

I've got two solutions at the same bytecount.

A train:

⊢⊃⊃∘(,/{⌽(+/⍳⍵-1)+⍳⍵}¨∘⍳)

Try it online!

And a dfn:

{⍵⊃⊃((⍳⍵),.{1+⍵-⍳⍺}+\⍳⍵)}

Try it online!

Both of these solutions first create the flipped triangle and then extract element at the index stated by the argument (1-based).

C#, 46 44 bytes

n=>Math.Pow((int)(Math.Sqrt(2*n)+.5),2)-n+1;

I port @Arnauld's solution. Thank you!

PHP, 35 Bytes

<?=((2*$argn)**.5+.5^0)**2-$argn+1;

Same formula that is used in Arnaulds Approach

Batch, 70 bytes

@set/ai=%2+1,j=%3+i
@if %j% lss %1 %0 %1 %i% %j%
@cmd/cset/ai*i+1-%1

Uses a loop to find the index of the triangular number at least as large as n.

Jelly, 8 7 bytes

RṁR€UFi

Thanks to @ErikTheOutgolfer for saving 1 byte!

Try it online!

How it works

RṁR€UFi  Main link. Argument: n

R        Range; yield [1, ..., n].
  R€     Range each; yield [[1], [1, 2], [1, 2, 3], ..., [1, ..., n]].
 ṁ       Mold the left argument like the right one, yielding
         [[1], [2, 3], [4, 5, 6], ...]. The elements of the left argument are 
         repeated cyclically to fill all n(n+1)/2 positions in the right argument.
    U    Upend; reverse each flat array, yielding [[1], [3, 2], [6, 5, 4], ...].
     F   Flatten, yielding [1, 3, 2, 6, 5, 4, ...].
      i  Index; find the first index of n in the result.

05AB1E, 9 bytes

·LD£í˜¹<è

Try it online!

Explanation

·L          # push range [1 ... 2n]
  D         # duplicate
   £        # split the first list into pieces with size dependent on the second list
    í       # reverse each sublist
     ˜      # flatten
      ¹<è   # get the element at index <input>-1

Array flattening unfortunately doesn't handle larger lists very well.
At the cost of 1 byte we could do ·t2z+ïn¹-> using the mathematical formula floor(sqrt(2*n)+1/2)^2 - n + 1 found on OEIS.

Alice, 27 bytes

Thanks to Sp3000 for the .C idea.

/o
\i@/.2:e2,tE*Y~Z.H2*~.C+

Try it online!

Explanation

I think there may be a shorter way to compute this using triangular numbers, but I thought this is an interesting abuse of a built-in, so here's a different solution.

The basic idea is to make use of Alice's "pack" and "unpack" built-ins. "Pack", or Z, takes two integers maps them bijectively to a single integer. "Unpack", or Y, inverts this bijection and turns one integer into two. Normally, this can be used to store a list or tree of integers in a single (large) integer and recover the individual values later. However, in this case we can use the functions in the opposite order, to let the nature of the bijection work for us.

Unpacking one integer into two integers basically consists of three steps:

  1. Map ℤ → ℕ (including zero) with a simple "folding". That is, map negative integers to odd naturals, and non-negative integers to even naturals.
  2. Map ℕ → ℕ2, using the Cantor pairing function. That is, the naturals are written along the diagonals of an infinite grid and we return the indices:

       ...
    3  9 ...
    2  5 8 ...
    1  2 4 7 ...
    0  0 1 3 6 ...
    
       0 1 2 3
    

    E.g. 8 would be mapped to the pair (1, 2).

  3. Map 2 → ℤ2, using the inverse of step 1 on each integer individually. That is, odd naturals get mapped to negative integers, and even naturals get mapped to non-negative integers.

To pack two integers into one, we simply invert each of those steps.

Now, we can see that the structure of the Cantor pairing function conveniently encodes the triangle we need (although the values are off-by-one). To reverse those diagonals, all we need to do is swap the x and y coordinates into the grid.

Unfortunately, since all three of the above steps are combined into a single built-in Y (or Z), we need to undo the ℤ → ℕ or ℕ → ℤ mappings ourselves. However, while doing so we can save a couple of bytes by directly using + → ℤ or ℤ → ℕ+ mappings, to take care of the off-by-one error in the table. So here is the entire algorithm:

  1. Map + → ℤ using (n/2) * (-1)n-1. This mapping is chosen such that it cancels the implicit ℤ → ℕ mapping during unpacking, except that it shifts the value down by 1.
  2. Unpack the result into two integers.
  3. Swap them.
  4. Pack the swapped values into a single integer again.
  5. Map ℤ → ℕ+ using |2n| + (n≥0). Again, this mapping is chosen such that it cancels the implicit ℕ → ℤ mapping during packing, except that it shifts the value up by 1.

With that out of the way, we can look at the program:

/o
\i@/...

This is simply a framework for linear arithmetic programs with integer input and output.

.    Duplicate the input.
2:   Halve it.
e    Push -1.
2,   Pull up the other copy of the input.
t    Decrement.
E    Raise -1 to this power.
*    Multiply. We've now computed (n/2) * (-1)^(n-1).
Y    Unpack.
~    Swap.
Z    Pack.
.H   Duplicate the result and take its absolute value.
2*   Double.
~    Swap with other copy.
.C   Compute k-choose-k. That's 1 for k ≥ 0 and 0 for k < 0.
+    Add. We've now computed |2n| + (n≥0).

05AB1E, 30 bytes

U1V[YLO>X›iYLOX-UY<LO>X+,q}Y>V

Try it online!

Octave, 71 68 bytes

3 bytes saved thanks to Conor O'Brien.

x=triu(ones(n=input('')));x(~~x)=1:nnz(x);disp(nonzeros(flip(x))(n))

This doesn't work for large inputs due to memory limitations.

Try it online!

Explanation

Consider input n = 4. The code first builds the matrix

 1     1     1     1
 0     1     1     1
 0     0     1     1
 0     0     0     1

Then it replaces nonzero entries in column-major order (down, then across) by 1, 2, 3 ... :

 1     2     4     7
 0     3     5     8
 0     0     6     9
 0     0     0    10

Then it flips the matrix vertically:

 0     0     0    10
 0     0     6     9
 0     3     5     8
 1     2     4     7

Finally, it takes the n-th nonzero value in column-major order, which in this case is 6.

C (gcc), 48 bytes

k,j,l;f(n){for(k=j=0;k<n;)l=k,k+=++j;n=1+k-n+l;}

Try it online!

Probably suboptimal, but I'm pretty happy with this one. Uses the fact that

NTFN = TN + A057944(N) - N + 1

(If I wrote the formula down correctly, that is.)

Jelly, 8 bytes

Ḥ½+.Ḟ²‘_

Try it online!

Port of my MATL answer.

MATL, 15 11 bytes

EX^.5+kUG-Q

Try it online!

This uses the formula

a(n) = floor(sqrt(2*n)+1/2)^2 - n + 1.