| Bytes | Lang | Time | Link |
|---|---|---|---|
| 039 | Juby | 250504T154305Z | Jordan |
| 328 | 64bit Aarch64 assembly | 250130T042041Z | petroleu |
| 163 | Bespoke | 250116T182014Z | Josiah W |
| 018 | Kona | 250116T151813Z | Abstract |
| 045 | Python | 250114T173646Z | Username |
| 003 | Vyxal 3 l | 250113T050244Z | lyxal |
| 005 | Uiua | 240331T123954Z | noodle p |
| 014 | Uiua | 240131T202929Z | Adelie |
| 018 | dc | 231226T233749Z | itzjacky |
| 010 | TIBASIC TI83/84 | 231225T001810Z | Saltmast |
| 027 | Haskell | 231223T065012Z | qwr |
| 021 | Perl 5 p | 231223T063243Z | Xcali |
| 020 | R 4.1+ | 231223T032212Z | qwr |
| 004 | Nekomata + e | 230702T012350Z | alephalp |
| 091 | TypeScript’s type system | 231221T182930Z | noodle p |
| 024 | Desmoslang | 230530T043752Z | Dadsdy |
| 004 | 05AB1E | 210329T203418Z | Makonede |
| 003 | Vyxal | 220626T061745Z | lyxal |
| 027 | Desmos | 220626T032558Z | Aiden Ch |
| 024 | Scala | 220209T200325Z | cubic le |
| 060 | tinylisp | 220209T173323Z | Giuseppe |
| 105 | Python 3 | 220209T163120Z | Mr.McNug |
| 024 | Fourier | 220209T150621Z | sinvec |
| 037 | Regex ECMAScript | 210321T085644Z | Deadcode |
| 004 | Husk | 201015T122741Z | Razetime |
| 039 | Python 3.8 prerelease | 200319T212430Z | RGS |
| 004 | cQuents | 200405T041626Z | PkmnQ |
| 026 | C gcc | 200320T204943Z | S.S. Ann |
| 024 | Python | 170522T203719Z | xnor |
| 004 | 05AB1E | 190312T184524Z | rev |
| 012 | Gol><> | 190214T035931Z | KrystosT |
| 080 | Alchemist | 190214T082317Z | Jo King |
| 036 | PowerShell | 190214T052113Z | mazzy |
| 004 | cQuents | 190214T011901Z | Stephen |
| 024 | APLNARS 12 chars | 190201T094332Z | user5898 |
| 006 | cQuents | 170801T000324Z | Stephen |
| 005 | Jelly | 170522T215107Z | Dennis |
| 004 | 05AB1E legacy | 181206T200850Z | Cowabung |
| 019 | R | 181206T190017Z | Robert S |
| 007 | Japt | 170522T205356Z | Oliver |
| 009 | J | 180111T013553Z | Bolce Bu |
| 007 | Japt | 170522T222931Z | Shaggy |
| 005 | Pyt | 171225T021857Z | mudkip20 |
| 010 | CJam | 171026T121106Z | aditsu q |
| 021 | JavaScript ES8 | 171026T091935Z | user7520 |
| 007 | TIBASIC | 170523T032308Z | Scott Mi |
| 022 | Alice | 170522T214719Z | Luis Men |
| 023 | Java 8 | 170523T075232Z | Kevin Cr |
| 023 | Cubix | 170522T233649Z | MickyT |
| 042 | BrainFlak | 170523T152534Z | Wheat Wi |
| 095 | Whitespace | 170530T234558Z | Censored |
| 045 | C | 170530T100001Z | Soumik M |
| 022 | Excel | 170523T115025Z | Wernisch |
| 008 | 2Col | 170523T143619Z | Mayube |
| 006 | APL Dyalog | 170524T164516Z | user4180 |
| 030 | PowerShell | 170523T220602Z | briantis |
| 040 | BrainFlak | 170523T152636Z | Riley |
| 052 | Python | 170523T190059Z | Mr. Xcod |
| 026 | Fourier | 170523T153208Z | Beta Dec |
| 023 | Octave | 170523T134926Z | Luis Men |
| 028 | ><> | 170523T071747Z | Esolangi |
| 065 | VB.NET | 170523T133113Z | Brian J |
| 027 | JavaScript ES6 | 170522T205153Z | Arnauld |
| 006 | Neim | 170523T083257Z | Okx |
| 023 | Haskell | 170523T054922Z | Ørj |
| 047 | C gcc | 170523T060644Z | Leaky Nu |
| 005 | Brachylog | 170523T034315Z | user6213 |
| 062 | BrainFlak | 170523T032521Z | Nitrodon |
| 018 | Pari/GP | 170523T030556Z | alephalp |
| 028 | Mathematica | 170522T203741Z | ZaMoC |
| 017 | Perl 6 | 170522T212647Z | Sean |
| 054 | Clojure | 170522T222501Z | NikoNyrh |
| 030 | PHP | 170522T203526Z | Jör |
| 018 | JavaScript ES7 | 170522T211733Z | Shaggy |
| 006 | 05AB1E | 170522T214749Z | Neil A. |
| 016 | Mathematica | 170522T214651Z | user6198 |
| 072 | Batch | 170522T211500Z | Neil |
| 011 | CJam | 170522T204133Z | Luis Men |
| 019 | QBIC | 170522T204057Z | steenber |
| 025 | Python 2 | 170522T203655Z | Adnan |
| 010 | Retina | 170522T204812Z | Martin E |
| 004 | Jelly | 170522T203834Z | Jonathan |
| 005 | MATL | 170522T203647Z | DJMcMayh |
64-bit Aarch64 assembly, 32 bytes / 8 insns
f:
fmov d1, #8.0
fmov d2, #1.0
fmadd d1, d0, d1, d2
fsqrt d1, d1
frinti d0, d1
fcmp d0, d1
cset x0, eq
ret
This assumes that the input is a double-precision number in d0, and returns either 1 or 0 in x0; it would have a C signature of extern int f(double);
It copies the rest of the answers' insightful check for whether (8x + 1) is a square by first calculating the square root of (8x + 1), performing a rounding operation, and then checking for the result's equality with the square root, setting x0 to 1 if equal and 0 if different.
How to test (as in Termux)
Depends on GNU binutils and a C compiler like GCC or tcc.
Save the following as d1.s:
.globl f
f:
fmov d1, #8.0
fmov d2, #1.0
fmadd d1, d0, d1, d2
fsqrt d1, d1
frinti d0, d1
fcmp d0, d1
cset x0, eq
ret
Save the following as d-test.c:
extern int f(double);
int truthies[] = {
1,
3,
6,
10,
15,
21,
55,
276,
1540,
2701,
5050,
7626,
18915,
71253,
173166,
222111,
303031,
307720,
500500,
998991,
};
int falseys[] = {
2,
4,
5,
7,
8,
9,
11,
16,
32,
50,
290,
555,
4576,
31988,
187394,
501500,
999999,
};
void truthyTest(void) {
for (int i=0; i<sizeof(truthies)/sizeof(truthies[0]); i++) {
if (!f(truthies[i]))
exit(printf("Truthy test failed for %d\n", truthies[i]));
}
}
void falseyTest(void) {
for (int i=0; i<sizeof(falseys)/sizeof(falseys[0]); i++) {
if (f(falseys[i]))
exit(printf("Falsey test failed for %d\n", falseys[i]));
}
}
int main(void) {
truthyTest(); falseyTest();
}
Finally run the following commands; this compiles the executable and the executable should exit without outputting anything:
cc -o d-test d1.s d-test.c && ./d-test
Bespoke, 163 bytes
while I do love whatever kind of poly-gons
A,B,C side of triangle shape?favorite one
no,cant describe reasons
possibly something peculiar about triangle-s,stated I
If \$n\$ were a triangular number, its index would be \$\lfloor \sqrt{2 n} \rfloor\$; thus, this program calculates that number \$k\$, and checks whether \$2 n = k \cdot (k + 1)\$.
This program uses STACKTOP POW to calculate the square root; a power of -2 is considered a square root.
Kona, 18 Bytes
{1=4:.$(1+8*x)^.5}
Note that Kona functions are read from right to left. So first, we do (1+8*x)^.5 which calculates the square root of 8x+1. Next, .$ turns floating representation to integer; e.g. .$ 1.0 is equal to 1. Finally, 1=4: checks if the data type is equal to 1; i.e. if it is an integer. Thus the function outputs 1 if number is triangular and 0 otherwise.
Python, 45 bytes
x=int(input())*2;y=x**0.5//1;print(x==y*y+y)
Triangular number n = n(n+1)/2
Vyxal 3 -l, 3 (literate) bytes
0->n++ cumulative-sums contains
An exact port of Vyxal 2, but accidentally rediscovered.
Uiua, 5 bytes
∊\+⊸⇡
Try it: Uiua pad
Is the input a member of taking the cumulative sums of the range of 0 to the input?
Uiua, 14 bytes SBCS
Outputs 0 for false and 1 for true. Uses the "8n+1 is Perfect Square" method.
&p=⌊.√+1×8⋕&sc
Explanation
&p=⌊.√+1×8⋕&sc
&sc # Read line from stdin
⋕ # Parse string as number
+1×8 # Multiply by 8, then add 1
√ # Square root
. # Duplicate
⌊ # Floor
= # Compare for equality
&p # Print with newline
dc, 18 bytes
?8*1+dvd*[0]sI=Izp
Prints 1 if triangular, 0 if not.
Explanation:
? get input (call it x)
8*1+ let y = 8 * x + 1
d duplicate
vd* square root, then square (dc's sqrt has integer precision)
[0]sI=I if y == sqrt(y)^2, leave 0 on stack, otherwise leave nothing
zp print stack depth
TI-BASIC (TI-83/84) , 28 26 10 bytes
saved 2 bytes by using a different method
count was way off
:fPart(√(8Ans+1))=0
Haskell, 27 bytes
This is my first time using Haskell rather than SML (I couldn't find a scan function), so I don't know if this is a valid answer, but it is a valid function in the interpreter.
\x->elem x(scanl(+)0[1..x])
R (4.1+), 20 bytes
R has a vectorized cumsum(), which can come in handy for time series data.
\(x)x%in%cumsum(1:x)
Nekomata + -e, 4 bytes
8*→√
8*→√
8* Multiply the input by 8
→ Increment
√ Check if it's a perfect square
Nekomata + -e, 4 bytes
R∫$Ĩ
R∫$Ĩ
R Range from 1 to input
∫ Cumulative sum
$Ĩ Check if it contains the input
TypeScript’s type system, 91 bytes
//@ts-ignore
type F<N,A=[],I=N["length"]>=N extends[...infer R,0]?F<R,[1,...R,...A],I>:A[I]
This is a generic type F taking a unary number N as a tuple of N zeroes. I never would have expected a challenge like this to be under 100 bytes in TS types, but in this instance it’s quite doable. This is almost definitely ungolfable.
This works by creating the string 1101001000100001…, which contains N ones separated by as many zeroes as there are already added ones, and indexing into this string with N.
Explanation of the code:
//@ts-ignore - Suppress any type errors on the following line.
type F<
N, // N is a tuple type of 0s
A=[], // A becomes the string, starts as an empty list
I=N["length"] // I is the original N which we use to index at the end
>=
N extends[...infer R,0] // If a 0 fits in N, take the difference R (i.e. decrement)
?F<R, // If that succeeded, recurse with N = R,
[1,...R,...A], // A with 1 then R prepended,
I> // and I kept as it was.
:A[I] // If it failed, N is 0, so index into A with the original number.
Desmoslang, 24 Bytes
0^{\mod((8*I+1)^{.5},1OT
05AB1E, 4 bytes
All of the following programs work:
ÅTθQ
ÅTI¢
ÅTIå
ÅTs¢
ÅTså
ÅT¹¢
ÅT¹å
Try every single one of these programs online!
ÅT is all triangular numbers \$≤\$ implicit input, θ is last element (a[-1]), Q is equality (a==b), I and ¹ are input (input()), ¢ is occurrences (a.count(b)), and å is membership (b in a).
Vyxal, 3 bytes
ɾ¦c
Try it Online! or Try a Test Suite Online!
Can be 2 bytes with the R flag.
The power of automatically swapping arguments based on types.
Explained
ɾ¦c
ɾ # The range [1..n]
¦ # Cumulative sums of that - this creates a list of the first n triangular numbers, which is guaranteed to include at least one number bigger than the input.
c # is the input in that list? The arguments popped are [input, triangles] but Vyxal is smart enough to realise that because a list will never be in a number, it can swap the arguments and perform the membership test.
Scala, 24 bytes
n=>math.sqrt(8*n+1)%1==0
Same approach as taken by many others here: check whether \$\sqrt{8n+1}\$ is an integer (via fractional modulo)
Python 3, 105 bytes
import math
n=int(input(""))
if float(math.sqrt(8*n+1)).is_integer():
print("y")
else:
print("n")
Regex (ECMAScript), 37 bytes
Warning: Despite this regex's small size, it contains a major spoiler. I highly recommend learning how to solve unary mathematical problems in ECMAScript regex by figuring out the initial mathematical insights independently. It's been a fascinating journey for me, and I don't want to spoil it for anybody who might potentially want to try it themselves, especially those with an interest in number theory. See this earlier post for a list of consecutively spoiler-tagged recommended problems to solve one by one.
So do not read any further if you don't want some advanced unary regex magic spoiled for you. If you do want to take a shot at figuring out this magic yourself, I highly recommend starting by solving some problems in ECMAScript regex as outlined in that post linked above.
This is the simplest natural number unary decision-function that, in order to be implemented in ECMAScript regex, absolutely requires an algorithm for generalized multiplication. This is in contrast to matching perfect squares and other powers, which can be done by dividing out prime factors individually (although the best golf is not achieved that way). Generalized multiplication can be implemented by prime factorization, and I did so on my initial try, but it takes 600+ bytes.
Remarkably, generalized multiplication can be implemented quite concisely in ECMAScript regex using the Chinese remainder theorem. The algorithm is discussed in my abundant numbers answer.
teukon posed the Triangular Numbers puzzle in 2014, after we had both figured out the best algorithm for generalized multiplication. I was not able to beat his golf on this problem; he managed to get it down to 37 bytes, but I was only able to get it down to 48 bytes. He's unlikely to ever create an account on CGCC, and I haven't been able to even get in contact with him since 2014. I feel this very elegant regex belongs on CGCC, though, and the ideas behind it were a joint effort between us, so I'm posting on his behalf:
^((((x*)x?)\3)x)(?=\4(\1*)\2*$)\1*$\5
^ # N = input number
( # \1 = n*2-1 or n*2+1
( # \2 = \1-1
( # \3 = n-1 or n
(x*) # \4 = n-1
x?
)
\3
)
x
)
(?=
\4(\1*)\2*$ # iff \1+\4*\1 == N, then the first match here must result in \5 == 0
)
\1*$\5 # test for divisibility by \1 and for \5 == 0 simultaneously
Including zero in the "truthy" category only costs 1 byte (bringing it to 38 bytes), using ECMAScript NPCG (non-participating/unset capture group) behavior:
^((((x*)x?)\3)x)?(?=\4(\1*)\2*$)\1*$\5
Doing so with NPCG-independent behavior costs 3 bytes, bringing it to 40 bytes:
^((((x*)x?)\3)x)(?=\4(\1*)\2*$)\1*$\5|^$
Returning the triangular root
48 bytes with zero-handling, based on the 38 byte true/false version:
^(?=((((x*)x?)\3)x)?(?=\4(\1*)\2*$)\1*$\5)x?\3\4
46 bytes without zero-handling, based on the 37 byte true/false version:
^(?=((((x*)x?)\3)x)(?=\4(\1*)\2*$)\1*$\5)x\3\4
I haven't tried golfing this down yet. There may be specific golf optimizations for returning the triangular root.
Python 3.8 (pre-release), 45 40 39 bytes
lambda n:0in[n:=n+~i for i in range(n)]
Try it online!, which is a golf of this more standard
lambda n,t=0:n in[t:=t+i for i in range(n+1)]
Try it online! Not a Python winner but it showcases the := walrus operator in a scenario where it could actually be used in the real world! Hehe
cQuents, 4 bytes
?Z+$
cQuents is literally made for these questions.
? # Query (Outputs if the input is in the sequence)
Z # Previous term of the sequencd
+$ # Plus the index (starts from 1)
Python, 24 bytes
lambda n:(8*n+1)**.5%1>0
Outputs False for triangular numbers, True for the rest. Checks if 8*n+1 is a perfect square. Python's float precision for square roots easily suffices for the challenge limits of n up to a million, first giving a false positive on n=6896076976160002 as found by Deadcode.
05AB1E, 4 bytes
ÅTI¢
Explanation:
ÅT Get list of triangle numbers less than or equal to the implicit input
I¢ Count occurrences of input in list
Gol><>, 12 bytes
I8*P12,X1%zh
6 bytes golfed off, courtesy of JoKing! A codebreakdown will be coming soon!
First version, 18 bytes
I8*P12,X1}:S(-Zh0h
I found a pretty simple formula for solving this, which helped golf this, since we are only looking to see if the number is triangular, rather than calculate it.
Link to wiki where I found the formula!
Code Breakdown!
I8*P //Multiply the output by eight
12,X //Get the square root
1} //Push a value for truthy output and put it on the bottom
:S(- //Check to see if it is a perfect squareroot, no floating point
Zh0h//If the difference is zero(perfect squareroot) output truthy, otherwise, push a falsey and output!
There is a way to remove 2 bytes, but it outputs the input plus one for truthy, which I don't think is to the specification of "You must pick two constant, distinct outputs to distinguish the two categories".
Alchemist, 80 bytes
_->In_n+s
f+b->f+a
f+0b->a
0f+n+a->b
0f+0a+n->n+f
0n+a+s->Out_n
0n+0a+s->Out_"1"
Subtracts increasing numbers from the input until it reaches 0, and checks if the counter is zero.
PowerShell, 36 bytes
for(;$args-gt$s){$s+=++$i}$s-in$args
This script is 6 bytes longer than the briantist's solution. The script works with any [long] (except for 0) and calculates only what is needed.
cQuents, 4 bytes
?Z+$
Explanation
?Z+$
Given input n,
? Mode query: output true if n is in sequence, false if n is not in sequence
Each term in the sequence equals
Z Previous term
+ +
$ current index (1-indexed)
APL(NARS) 12 chars, 24 bytes
{0=1∣√1+8×⍵}
It is done seen(copy) some other solution... it seems {1∣⍵} it is 0 when ⍵ is one int decimal with 0 digits afther the "." test:
f←{0=1∣√1+8×⍵}
{⍞←{1=f ⍵:' ',⍵⋄⍬}⍵⋄⍬}¨0..200
0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190
but i remember i wrote the solution to this a little +long, some time ago...
cQuents, 7 6 bytes
?b$
;$
Explanation
?b$ First program. Checks if the input is triangular.
? Mode: query. Returns true if the input is in the sequence, and false otherwise.
b$ Each item in the sequence is the secondary program, passed the current (1-based) index.
;$ Secondary program. Generates triangular numbers.
; Mode: series. Calculates the sum of the sequence up to the input.
$ Each item in the sequence is the current (1-based) index.
Jelly, 5 bytes
×8‘Ʋ
Background
Let n be the input. If n is the kth triangular number, we have
$$ n = \frac{k(k+1)}{2} \iff k^2+k-2n = 0 \iff k = \frac12 (-1 \pm \sqrt{1+8n}), $$
which means there will be a natural solution if and only if 1 + 8n is an odd, perfect square. Clearly, checking the parity of 1 + 8n is not required.
How it works
×8‘Ʋ Main link. Argument: n
×8 Yield 8n.
‘ Increment, yielding 8n + 1.
Ʋ Test if the result is a perfect square.
05AB1E (legacy), 4 bytes
ÅTs¢
Explanation:
ÅT //push all triangle numbers <= (implicit) input
s //push input onto stack
¢ //count occurrences of input in triangle numbers (i.e. 1 if triangle, 0 if not)
I'm using 05AB1E (legacy) since it pre-dates this challenge, but it works in current 05AB1E as well
R, 23 19 bytes
Similar approach as other answers. Checks to see if 8x+1 is a perfect square.
-4 bytes thanks Giuseppe and MickyT.
!(8*scan()+1)^.5%%1
Japt, 10 7 bytes
Saved 3 bytes thanks to @Luke and @ETHproductions
*8Ä ¬v1
Explanation:
*8Ä ¬v1
¬ // Square root of:
*8 // Input * 8
Ä // +1
v1 // Return 1 if divisible by 1; Else, return 0
õ å+ øU
Explanation:
õ å+ øU
õ // Create a range from [1...Input]
å+ // Cumulative reduce by addition
øU // Does it contain the input?
J, 10 9 Bytes
Triangular number of bytes as well :)
-1 Byte thanks to @FrownyFrog
0=1|2!inv
Explanation:
2! | n choose 2
inv | Inverse
0=1| | Test if it's an integer
Could have been 7 bytes if the truthy/falsy values didn't have to be constant.
Works since n choose 2 is n!/2!(n-2)! = n*(n-1)/2
I don't know of any shorter ways to test for integers, previously I had been using (=<.)
Pyt, 5 bytes
←Đř△∈
Explanation:
← get input
Đ duplicate input (on stack twice)
ř push [1,...,input] onto stack
△ calculate the kth triangle number for each element k in the array
∈ check if input is in array of triangle numbers
Longer but faster way, 9 bytes
←Đ2*√⌈ř△∈
Explanation:
← get input
Đ duplicate input (on stack twice)
2* double input
√⌈ ceiling of the square root
ř push [1,...,value from previous step] onto stack
△ calculate the kth triangle number for each element k in the array
∈ check if input is in array of triangle numbers
JavaScript (ES8), 21 bytes
a=n=>!((8*n+1)**.5%1)
TI-BASIC, 10 7 bytes
-3 thanks to @lirtosiast
:not(fPart(√(8Ans+1
Takes input on X. Checks if √(8X+1) is a whole number
Alice, 38 22 bytes
A lot of bytes saved thanks to Martin and Leo
/ i \2*.2RE.h*-n/ o @
There is a trailing newline. Outputs 1 for triangular, 0 otherwise.
Explanation
This uses the same approach as my CJam answer, only clumsier. In linearized form, the program becomes
i2*.2RE.h*-no@
where the i and o are actually in ordinal mode.
Consider input 21 as an example.
i Input integer STACK: 21
2* Multiply by 2 STACK: 42
. Duplicate STACK: 42, 42
2RE Integer square root STACK: 42, 6
. Duplicate STACK: 42, 6, 6
h Increment STACK: 42, 6, 7
* Multiply STACK: 42, 42
- Subtract STACK: 0
n Logical negation STACK: 1
o Output integer STACK:
@ End program
Java 8, 58 48 23 bytes
n->Math.sqrt(8*n+1)%1>0
Port of @xnor's amazing Python answer.
-25 bytes by using a Java 8 lambda instead of Java 7 method (and Math.sqrt(...) instead of Math.pow(...,.5)).
Cubix, 23 24 25 bytes
I1Wq/)s.;0..s;p-?\.+O@u
0 for truthy and nothing 0 for falsey. Brutes forces by incrementing counter, adding to cumulative sum and comparing to input. Now to try and fit it on a 2x2x2 cube. Did it!
I 1
W q
/ ) s . ; 0 . .
s ; p - ? \ . +
O @
u .
/Reflect to to face.I10\get integer input, push 1 (counter), push 0 (sum) and reflect+s;p-loop body. Add sum and counter, drop previous sum, raise input and subtract?Test the result of the subtraction- For 0 result carrying on straight ahead
\.uO@reflect to bottom face, no-op, U-turn, output and halt. - For positive result turn right onto bottom face and
@halt - For negative result turn left
;qWs)/sudrop subtraction, put input to bottom, shift left, swap counter and sum, increment counter, reflect, swap sum and counter, U-turn onto main loop body.
- For 0 result carrying on straight ahead
Brain-Flak, 42 bytes
(([{}](<((())<>)>))<>){<>({}({}({})))}{}{}
Explanation
The goal of this program is to create a state on two stacks and perform constant operation on both stacks until one of them zeros, we can then output depending on which stack we are on. This is similar to programs that determine the sign of a number. These programs put n on one stack and -n on the other and add one and switch stacks until one of the stacks is zero. If the number was negative in the first place the first stack will hit zero, if the number was positive the other stack will hit zero.
Here we create two stacks one that subtracts consecutive numbers from the input and one that just subtracts one. The one that subtracts consecutive numbers will only terminate if the number is triangular, (other wise it will just pass zero and keep going into the negatives). The other one will always terminate for any positive number, but will always do so slower than the first, thus non-triangular numbers will terminate on that stack.
So how do we set up stacks so that the same operation subtracts consecutive numbers on one and subtracts one on the other? On each stack we have the input on top so that in can be checked, below that we have the difference and below that we have the difference of the difference. Each time we run we add the "difference of the difference" to the regular "difference" and subtract that from the input. For the stack that checks for triangularity we set our double difference to be 1 so that we get consecutive integers each time we run, for the other stack we set it to 0 so that we never change the difference, that is it always stays 1. Here is how the stack is set up at the beginning, where n is the input:
-n -n
0 1
1 0
When we finally do terminate we can use these differences to check which stack we are on we pop the top two values and we get 1 for a triangular number and 0 for a non-triangular number.
Annotated code
(([{}](<((())<>)>))<>) Set up the stack
{ While
<> Switch stacks
({}({}({}))) Add bottom to second to bottom, add second to bottom to top
} End while
{}{} Pop the top two values
Here's a 50 byte solution I like as well.
{(({}[()]))}(([[]])<>){({}{}())<>}({}{()<><{}>}{})
Whitespace, 95 bytes
Visible representation:
SSNSNSTNTTNSSSNSSSTNTSSSSNSSNSSSSTNTSSSTSSNSSSTSNTSTSSSNTTTTSSTSNSNTSNNTTSNSSSTNTNSTNSSNSSNTNST
Reads the number from stdin. If it is triangular, it outputs 0 to stdout. Otherwise, it outputs 10.
Disassembly:
push 0
dup
inum
loop:
push 1
add
dup
dup
push 1
add
mul
push 2
div
push 0
get
sub
dup
jz match
jn loop
push 1
pnum
match:
push 0
pnum
The used technique is a simple brute force search through all possible triangular numbers, but for the given limits that is plenty. Using my own whitespace JIT compiler it takes 0.6 milliseconds to prove that 106 is not a triangular number and about 20 seconds to prove that 1018 is not a triangular number.
C, 45 bytes
a,i;f(n){while(i<=n&&(a=i*i+i++!=2*n));a=!a;}
Explanation:
a,i; - data definition with no type or storage class is allowed in C (gives a warning). Doesn't work in C++ though.
f(n) - This behavior(parameter without type - by default assigned an integer type) is to provide backwards compatibility with older K&R version of C.
while() - loop is self explanatory
a=!a; - the return value of the function should be in "eax" register, but it is often also used as scratch register by calee. So we do a negation operation to store the answer in the eax which gets returned.
Excel, 31 22 bytes
9 bytes saved thanks to Octopus
Outputs TRUE for triangular numbers. Else FALSE. Checks if 8*n+1 is a perfect square.
=MOD(SQRT(8*B1+1),1)=0
2Col, 8 bytes [non-competing]
*8
+1
Sq
Try it on 2Collide
Braingolf got boring so now I'm making a new language. Link leads to the current 2Col interpreter in TIO, with the above code already inserted. 3rd argument is input.
2Col is a language where each line is a 2 character expression of some form. It's what I like to call an "Accumulator-based" language. It works like Stack-based languages, except the "stack" can only contain a single item.
Explanation:
Implicit input to Cell
*8 Multiply Cell by 8
+1 Add 1 to Cell
Sq Return true if Cell is square number
Implicit: Print final line's return value
APL (Dyalog), 6 bytes
⊢∊+\∘⍳
Explanation
⊢∊+\∘⍳
⍳ Creates a range from 1 to the right_argument
+\ Cumulative sum of this range; 1 1+2 1+2+3 .. 1+2+..+n. These are the triangular numbers
⊢∊ Does the right argument belong to this list of integers in this cumulative sum
Outputs 0 for false and 1 for true.
PowerShell, 31 30 bytes
"$args"-in(1..1e6|%{($s+=$_)})
Nice and slow brute force method. Make an array of every sum of 1 through 106, and see if the argument is in there.
Brain-Flak, 40 bytes
(([{}](((()))<>))<>){<>({}({}({})))}{}{}
Wheat Wizard and I had a duel over this question. When we decided to post our solutions we were tied at 42 bytes, but I found a 2 byte golf of his solution. We decided that would count as the tie breaker (my solution is below).
Explanation:
# Set up the stacks like this: -input
1 -input
1 1
(([{}](((()))<>))<>) ^
# Output 1 for triangular and 0 for non-triangular
{<>({}({}({})))}{}{}
For a full explanation please see Wheat Wizard's answer.
Brain-Flak, 42 bytes
(([({})])<>){(({}())<>{}({})){((<>))}{}{}}
Outputs 0\n (literal newline) for truthy, and the empty string for falsy.
The idea is to subtract 1 then 2 then 3 all the way up to the input. If you hit 0, then you know this is a triangular number, so you can stop there.
Try it online! (truthy)
Try it online! (falsy)
# Push -input on both stacks. One is a counter and the other is a running total
(([({})])<>)
# Count up from -input to 0
{
# Push the new total which is: (counter += 1) + total (popped) + input (not popped)
# This effectively adds 1, then 2, then 3 and so on to the running total
(({}())<>{}({}))
# If not 0
{
# Push to 0s and switch stacks to "protect" the other values
((<>))
# End if
}
# Pop the two 0s, or empty the stack if we hit 0
{}{}
# End loop
}
Here's a 46 byte solution that I found interesting.
{<>(({}())){({}[()]<>{(<({}[()])>)}{}<>)}{}<>}
Outputs 0\n (literal newline) for truthy, the empty string for falsy.
The idea is to count down from input by consecutive numbers, 1 at a time. E.g. input - (1) - (1,1) - (1,1,1). Each time we subtract, if we aren't at 0 yet, we leave an extra value on the stack. That way, if we are at 0 and are still subtracting when we pop we remove the last value on the stack. If the input was a triangular number, we will end exactly at 0, and wont pop the 0.
Try it online! truthy
Try it online! falsy
# Implicit input (call it I)
# Until we reach 0, or the stack is empty
{
# Add 1 to the other stack and push it twice. This is our counter.
<>(({}()))
# While counter != 0
{
# counter -= 1
({}[()]
# if I != 0
<>{
# I -= 1, and push 0 to escape the if
(<({}[()])>)
# End if
}
# Pop from the stack with I. This is either the 0 from the if, or I
{}
# Get ready for next loop End while
<>)
# End While
}
# Pop the counter that we were subtracting from
{}<>
# End Until we reach 0, or the stack is empty.
}
Python - 52 bytes
Note: I know that the other two Python answers are much shorter, but this is the old-school way, more of a by-hand algorithm
n=input();i=s=0
while s<n:s=(i*i+i)/2;i+=1
print s>n
Octave, 23 bytes
@(n)sum(1:sqrt(2*n))==n
This is an anonyous function that returns true (displayed as 1) for triangular numbers and false (0) otherwise.
><>, 30 28 bytes
-2 bytes thanks to lanlock4
Assumes input is on the stack. Outputs either a 1 or 0.
0v
1<~v!?(}:{:,2*+1::+
n={<;
This was fun. I'm new to ><>, and I'd welcome any suggestions for golfing.
This starts with n=1, then continually increments n while n(n-1)/2 is less than the input number. Once the loop terminates, it prints 1 if n(n-1)/2 is equal to the input number, 0 otherwise.
VB.NET, 65
Sub T(n,j)
j=Math.Sqrt(8*n+1)
Console.Write(CInt(j)=j)
End Sub
Like other answers, determines if 8n + 1 is an integer or not.
Explanation:
Sub T(n,j) ' start the method, use n as the triangle number to check
' declare j here as well for use later, saving 4 bytes over a "dim j" call
j=Math.Sqrt(8*n+1) ' get the square root
Console.Write( ' write out the answer, either "True" or "False"
' it saves two bytes to do "Sub/End Sub" with "Console.Write()"
' over "Function/End Function" with "return "
CInt(j) ' round to the nearest integer (cast to int, but VB rounds instead of truncating)
=j) ' compare against the sqrt
JavaScript (ES6), 30 27 bytes
Saved 2 bytes thanks to kamoroso94
f=(n,k)=>n>0?f(n+~k,-~k):!n
Test cases
f=(n,k)=>n>0?f(n+~k,-~k):!n
console.log('Testing truthy test cases');
console.log(f(1))
console.log(f(3))
console.log(f(6))
console.log(f(10))
console.log(f(15))
console.log(f(21))
console.log(f(55))
console.log(f(276))
console.log(f(1540))
console.log(f(2701))
console.log(f(5050))
console.log(f(7626))
console.log(f(18915))
console.log(f(71253))
console.log(f(173166))
console.log(f(222111))
console.log(f(303031))
console.log(f(307720))
console.log(f(500500))
console.log(f(998991))
console.log('Testing falsy test cases');
console.log(f(2))
console.log(f(4))
console.log(f(5))
console.log(f(7))
console.log(f(8))
console.log(f(9))
console.log(f(11))
console.log(f(16))
console.log(f(32))
console.log(f(50))
console.log(f(290))
console.log(f(555))
console.log(f(4576))
console.log(f(31988))
console.log(f(187394))
console.log(f(501500))
console.log(f(999999))
Non-recursive version (ES7), 19 bytes
Port of Adnan's answer.
x=>(8*x+1)**.5%1==0
Neim, 6 bytes
𝐈Γ𝐈𝐬)𝕚
Explanation:
𝐈 Inclusive range; [1 .. input]
Γ For each...
𝐈 Inclusive range; [1 .. element]
𝐬 Sum
) End for each
𝕚 Check that the input is in the list
Haskell, 23 bytes
EDIT:
- -1 byte: @xnor got rid of parentheses with a
$.
An anonymous function taking an Int and returning a Char.
Output is '1' for triangular numbers and '0' for others.
(!!)$show.(10^)=<<[0..]
- Use as
((!!)$show.(10^)=<<[0..]) 998991. Generates the numbers 1, 10, 100, 1000, ..., converts those to strings, and concatenates them. Then indexes into the resulting infinite string
"1101001000100001000001000000...
Brachylog, 5 bytes
≥ℕ⟦+?
Explanation
≥ℕ⟦+?
≥ℕ There is a number from 0 to {the input} inclusive
⟦ such that the range from 0 to that number
+ has a sum
? that equals the input
Brain-Flak, 62 bytes
(([(({}))])<>){(({}())<>{}({})){(<><>)}{}<>}<>([[]]()()()<>{})
Explanation
Effectively, this code starts with n and subtracts 1, 2, 3, ... n. If an intermediate result is 0, this is marked by decreasing the size of the left stack.
(({})) duplicate input n
([ ]) push -n as accumulator
( <>) push -n on other stack as counter
{ } while counter is nonzero
({}()) increment counter
<>{} add to accumulator
({}) add stored copy of n (effectively, this adds a counter that starts at 1 instead of -n)
( ) push as new accumulator value
{(<><>)}{} If accumulator is zero, shrink the stack by one
<> switch back to right stack
<> move to left stack
[[]]()()() 3 minus height of left stack (which is 2 if n is triangular and 3 otherwise)
<>{} move back to right stack and pop zero from loop
( ) push answer
Pari/GP, 18 bytes
n->issquare(8*n+1)
There is a built-in to test if a number is a polygonal number, but it is one byte longer.
Pari/GP, 19 bytes
n->ispolygonal(n,3)
Mathematica, 28 bytes
!Accumulate@Range@#~FreeQ~#&
Perl 6, 17 bytes
{$_∈[\+] 1..$_}
Just checks whether $_, the input to the function, is equal to any of the elements of the triangular addition reduction (1, 1+2, ..., 1+2+...+$_).
Clojure, 54 bytes
#(and(some #{%}(reductions +(rest(range(max % 3)))))1)
I wish various truthy values were allowed so I didn't need to coerce them all to 1 with a penalty of 6 bytes.
Without caring about edge cases of 0 or 1, and allowing any truthy value this would have been just 35 bytes:
#(some #{%}(reductions +(range %)))
PHP, 30 Bytes
Prints 1 for true and nothing for false
<?=fmod(sqrt(8*$argn+1),2)==1;
PHP, 37 Bytes
Prints 1 for true and nothing for false
<?=($x=sqrt($q=2*$argn)^0)*$x+$x==$q;
JavaScript (ES7), 19 18 bytes
From my answer to a related question.
Outputs false for triangular numbers or true for non-triangular, as permitted by the OP.
n=>(8*n+1)**.5%1>0
Try It
f=
n=>(8*n+1)**.5%1>0
oninput=_=>o.innerText=f(+i.value)
<input id=i type=number><pre id=o>
05AB1E, 7 6 bytes
EDIT: Thanks to @Dennis: Saved a byte because I forgot about the increment operator
8*>t.ï
n is triangular if sqrt(8n + 1) is an integer
How it works
8* # multiply implicit input by 8
> # add one
t # sqrt
.ï # is integer
Mathematica, 16 bytes
OddQ@Sqrt[1+8#]&
Essentially a port of xnor's Python solution. Outputs True for triangular numbers, False otherwise.
Batch, 72 bytes
@set/aj=i=0
:l
@if %1% gtr %j% set/aj+=i+=1&goto l
@if %1==%j% echo 1
Outputs 1 on success, nothing on failure. Works for zero too, although not requested by the question for some reason.
CJam, 11 bytes
ri2*_mQ_)*=
Outputs 1 for triangular, 0 otherwise.
Explanation
Consider input 21.
ri e# Input integer. STACK: 21
2* e# Multiply by 2. STACK: 42
_ e# Duplicate. STACK: 42, 42
mQ e# Integer square root. STACK: 42, 6
_) e# Duplicate, increment. STACK: 42, 6, 7
* e# Multiply. STACK: 42, 42
= e# Equal? STACK: 1
QBIC, 21 19 bytes
[:|p=p+a~p=b|_x1}?0
Explanation
[ | FOR a = 1 to
: b (read from the cmd line)
p=p+a increment p by a (+1, +2, ...) (p is 0 at QBIC start)
~p=b| IF p == b ; we've hit a triangular number!
_x1 THEN QUIT, printing 1
} Close the IF and the FOR
?0 We didn't quit early, so print 0
Retina, 10 bytes
(^1|1\1)+$
Input is in unary. Output is 0 or 1.
Try it online! (As a test suite that does decimal-to-unary conversion for convenience.)
Explanation
This is the most basic exercise in forward-references. Most people are familiar with backreferences in regex, e.g. (.)\1 to match a repeated character. However, some of the more advanced flavours allow you to use a backreference before or inside the group it's referring to. In that case, it's usually called a forward-reference. This can make sense if the reference is repeated. It might not be well defined on the first iteration, but on subsequent iterations, the later or surrounding group has captured something and can be reused.
This is most commonly used to implement recurrent patterns on unary strings. In this case, we try to match the input as the sum of consecutive integers:
( # This is group 1, which we'll repeat 1 or more times.
^1 # Group 1 either matches a single 1 at the beginning of the string.
| # or
1\1 # It matches whatever the previous iteration matched, plus another
# 1, thereby incrementing our counter.
# Note that the first alternative only works on the first iteration
# due to the anchor, and the second alternative only works *after*
# the first iteration, because only then the reference is valid.
)+
$ # Finally, we make sure that we can exactly hit the end of the
# string with this process.
Jelly, 4 bytes
R+\ċ
How?
R+\ċ - Main link: n
R - range(n) -> [1,2,3,...,N]
\ - cumulative reduce by:
+ - addition -> [1,3,6,...,T(N)]
ċ - count occurrences of right (n) in left -> 1 if triangular, 0 otherwise
MATL, 5 bytes
t:Ysm
Explanation:
t % Duplicate input
: % Range(1, input)
Ys % Cumulative sum. This will push the first *n* triangular numbers
m % ismember. Pushes true if the input is contained within the array we just pushed
