| Bytes | Lang | Time | Link |
|---|---|---|---|
| 258 | jBasher2 | 250909T150136Z | madeforl |
| 018 | YASEPL | 250903T134302Z | madeforl |
| 014 | Uiua | 250704T014813Z | ErikDaPa |
| 026 | Perl 5 p | 250703T145218Z | Xcali |
| 016 | TIBASIC TI83 Plus | 250703T140943Z | madeforl |
| 007 | Vyxal 3 | 250703T115541Z | Themooni |
| 026 | JavaScript ES7 | 170428T003420Z | Arnauld |
| 011 | Japt | 230103T173235Z | Shaggy |
| 019 | J | 230103T161402Z | Conor O& |
| 023 | Julia 1.0 | 230102T023539Z | DialFros |
| 032 | Python 3 | 230102T023028Z | DialFros |
| 008 | Vyxal | 230102T030639Z | naffetS |
| 012 | Pyt | 171226T023812Z | mudkip20 |
| 031 | Haskell | 171226T044514Z | Wheat Wi |
| 078 | tinylisp | 171226T053615Z | DLosc |
| 006 | Husk | 171226T040416Z | ბიმო |
| 025 | J | 170507T183431Z | ljeabmre |
| 027 | APL Dyalog | 170507T135142Z | user4180 |
| 044 | C# | 170428T153140Z | aloisdg |
| 035 | PHP | 170428T135236Z | Jör |
| 070 | Batch | 170428T134917Z | Neil |
| 007 | Jelly | 170428T002301Z | Dennis |
| 009 | 05AB1E | 170428T113143Z | Emigna |
| 027 | Alice | 170428T104712Z | Martin E |
| 030 | 05AB1E | 170428T020438Z | Eduardo |
| 068 | Octave | 170428T005606Z | Luis Men |
| 048 | C gcc | 170428T005828Z | Conor O& |
| 008 | Jelly | 170428T004241Z | Luis Men |
| 011 | MATL | 170428T002710Z | Luis 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
TI-BASIC (TI-83 Plus), 16 bytes
Input N
round(√(2N),0)²-N+1
hooray!
Vyxal 3, 7 bytes
d√◌²?‹-
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
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Ô
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.]
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.
Python 3, 37 35 32 bytes
lambda n:round((2*n)**.5)**2-n+1
Port of Arnauld's JS answer.
-3 thx to @Steffan
Haskell, 31 bytes
r=round
f n=r(sqrt$2*n)^2-r n+1
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)
(!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
(!!)$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
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.
- If the current triangular number is less than N, recurse to the next row of the triangle. (We treat the top row as row 2 to make the math simpler.)
- Otherwise, the flipped version of N is (T-N)+(T-R)+2.
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
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)+⍳⍵}¨∘⍳)
And a dfn:
{⍵⊃⊃((⍳⍵),.{1+⍵-⍳⍺}+\⍳⍵)}
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!
- Pow of 0.5 is Sqrt. 2 bytes saved!
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!
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£í˜¹<è
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+
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:
- Map ℤ → ℕ (including zero) with a simple "folding". That is, map negative integers to odd naturals, and non-negative integers to even naturals.
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 3E.g.
8would be mapped to the pair(1, 2).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:
- 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.
- Unpack the result into two integers.
- Swap them.
- Pack the swapped values into a single integer again.
- 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).
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.
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;}
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.)