text:
Infinite Sequence of Unique Random Integers
Output an infinite sequence of positive integers, such that, for each element in the sequence, all positive integers that have not yet been output have a positive probability of being chosen, and no value is repeated.
For example, if the first integer is 3, then 3 may not be output again, but all other positive integers have a positive probability of being chosen for the second integer.
Acceptable output methods

Writing to STDOUT, with a consistent, unambiguous separator between integers (such as a newline), with output prior to termination of the program
A named or unnamed function which returns an infinite iterable (such as a Python generator)
A named or unnamed function which outputs the sequence one integer at a time each time it is called within a single execution of the program
A named or unnamed function or program which outputs the next integer in the sequence when called with the previous integer(s) as its sole argument(s) (the first call may either take no arguments or take a seed argument, which may be included in the arguments to later calls)

Rules

There will be no input except an optional seed value, which will be an infinite sequence of random bits.
Submissions must be capable of producing different outputs given different initial conditions (outputting the same sequence every time is not acceptable).
Each element of the sequence must be chosen randomly out of the valid elements (positive integers not already present in the sequence).
You may assume that you have infinite memory available.
You may assume that any real numbers returned by a PRNG are infinite-precision. In other words, if you have a function called rand that returns a random value in [0, 1), you may assume every real value in that interval has a positive probability of being chosen, rather than just the subset of the reals that are representable with floats.
Each integer must be output in a finite amount of time after the last integer (so you can't wait until program termination to output part of the sequence). The first integer must be output in a finite amount of time after the program is started or the function is called.

So, shouldn't the first number (and all the following ones) have an infinite number of digits?

@Arnauld Integers are finite. You're outputting an infinite number of integers, not integers with infinite length (which don't exist).

@LuisMendo I'm not sure what you're asking.

What I mean is that if the sequence really is infinite (which of course is not going to be the case in practical implementations), the number of digits of the numbers tends to infinity. And if each element of the sequence is chosen randomly out of the valid elements, I don't see why the first numbers of the sequence should be small ones. But I may be missing something.

@Arnauld There is no requirement that all valid integers have equal probability (in fact, there can't be, because then that probability would be infinitesimal). It's perfectly valid to have the probability of an integer n being chosen be 1/n, which would cause smaller values to have much larger probabilities than larger values.

Let us continue this discussion in chat.

Related.

Let us continue this discussion in chat.

Python 3, 137 127 123 138 117 99 98 bytes

A named or unnamed function which returns an infinite iterable (such as a Python generator)

from random import*
def f(x=[],y=1):
 while y in x or.5<random():y+=1
 yield y;yield from f(x+[y])

-10 bytes by putting the conditional in one line (Thanks, @Dennis)
-4 bytes by initializing r at the beginning of the loop
+15 bytes by remembering numbers can contain zeroes...
-21 bytes by renaming randint, and moving the condition in the head of the inner loop
-18 bytes by switching to a functional paradigm
-1 bytes by moving from or ...>.5 to .5<random() (thanks, @JonathanAllan)

The entire if statement can go on a single line.

@Mego Just switched to Python 3, I'm sure I can save characters elsewhere.

@JonathanAllan I guess I did... It wasn't intentional, it happened while I made it a generator after having read your answer... My Aceto answer is then also inspired by your answer.

That is a lot of golfing. nj

Python 2, 93 87 bytes
-3 bytes thanks to Uriel (move r=1 to beginning of the loop to avoid initialisation)
from random import*
a=[]
while 1:
 r=1
 while r in a or.5<random():r+=1
 a+=[r];print r

Try it online!
Keeps adding one while the number is either unavailable or a coin flip comes up heads.
Low numbers have much more probabilistic weight than high numbers.

you can cut 3 bytes by moving the r=1 to the beginning of the loop and deleting the third line

MATL, 10 bytes
`x1r/XktGm

Try it online!
Explanation
A candidate output, say n, is generated as ceil(1/r), where r is uniformly distributed on the interval (0,1). This ensures that every positive integer has a positive probability of being chosen as n (assuming infinite precision for r).
If n coincides with any of the previous numbers (taken as input) the process is repeated.
`       % Do...while
  x     %   Delete. This deletes the candidate number from the preceding iteration.
        %   In the first iteration it takes input implicitly and deletes it.
  1     %   Push 1
  r     %   Push random number uniformly distributed on (0,1)
  /     %   Divide
  Xk    %   Round up (ceil). This is the candidate output. It will only be valid
        %   if it's not present in the input
  t     %   Duplicate
  G     %   Push input: forbidden numbers
  m     %   Ismember. This will be used as loop condition
        % End (implicit). If condition is true, next iteration
        % Display (implicit)

Bash, 23 bytes
yes \ |nl|xargs shuf -e

Try it online!
yes \ prints infinite spaces, nl numbers lines, suff -e shuffless lines without repetition.

JavaScript, 62 bytes
A full program that picks a single random value in [0 .. 1] and expressed it as a continued fraction, omitting elements that have been encountered before. This would produce a really infinite sequence if the initial value had an infinite precision. In practice, we are limited to what can be expressed in IEEE-854 format.
for(x=Math.random(),o=[];;)o[n=1/x|0,x=1/x-n,n]||alert(o[n]=n)

Demo
Here is a demo limited to 50 values and writing to the console instead.

for(x=Math.random(),o=[],i=0;i<50;)o[n=1/x|0,x=1/x-n,n]||console.log(o[i++,n]=n)

Would this output a single value in finite time in the imagined scenario where we have infinite precision?

@JonathanAllan Actually, I think so. A random real r with infinite precision must be an irrational number that maps to an infinite sequence of random integers An such that r = A0+1/(A1+1/(A2+1/...)), so any 'new' value of An can be picked in finite time.

That seems like you are suggesting that 0.5 is not a real number :/

The infinite precision really is important here. It assumes that the PRNG can support infinite precision and can't possibly generate exactly 0.5. Does that make sense? (It's more like 0. followed by an infinite number of random digits.)

Yeah I think the premise of infinite precision makes the question impossible to specify clearly to be honest. If 0.5 has zero chance of being output then so does every other real number too.

@JonathanAllan The way I see it, any rational real number can't possibly be generated indeed.

Let us continue this discussion in chat.

for(x=Math.random(),o=[];;o[n]||alert(o[n]=n))n=1/x|0,x=1/x-n

Aceto, 29 21 bytes

Writing to STDOUT, with a consistent, unambiguous separator between integers (such as a newline), with output prior to termination of the program

p<LL
 v`O
I?<\
0MLCnO

Push a zero, increment it and go in a random direction. Two of the directions lead back to the random direction field, one leads back to incrementation (so it is incremented a random amount of times).
When the fourth choice is made, we memorize and immediately load the value, then check whether it's contained in the stack already. If so, we jump to the origin and try again.
Otherwise, we load the value twice (once for printing, once for storage), print it and a newline and go back to the origin.

Massively favours low numbers, but there is a small chance for it to print any number at any point.

Haskell, 60 59 56 bytes
((a:b)#h)(n:r)|n=a:((h++b)#[])r|q<-a:h=(b#q)r
[1..]#[]

Takes the seed as an infinite list of Bool.
Usage example: ([1..]#[]) [True,False,False,True,True,False,True,True,False,True,False,True,True,False,False,False,False,False,False,True....] -> [1,4,3,5,2,7,8,6,15,...].
Try it online!
Start with the list [1..]. If the next element from the seed is False, skip the next element of the list. If it's a True, output the current element, remove it from the list and start from the beginning. h keeps track of the skipped elements and is prepended (-> h++b) to the list of available numbers in the True case.

What if the infinite list contains only 0's?

@Qwerp-Derp: then there's no output. Some of the other answers run into the same problem if the random function returns the same number over and over again. I'm just using the seed itself as the random sequence.

Clojure, 112 (or 119) 114 bytes
Update, uses 1 / (rand) to get an "infinite" range of bigints:
#(filter pos?(map first(reductions(fn[[v p]r](if(p r)[0 p][r(conj p r)]))[0#{}](for[i(range)](bigint(/(rand)))))))

Original:
#(filter pos?(map first(reductions(fn[[v p]r](if(p r)[0 p][r(conj p r)]))[0 #{}](for[i(range)](rand-int 2e9)))))

I'm hoping to see an alternative approach. Anyway, this will generate integers between 1 and 2e9, Java's integers are signed to the "real" maximum is 2147483647, which is 7 bytes longer expression (Integer/MAX_VALUE is even longer). 0 is used as an indication of a duplicate values and are filtered from the output sequence.

You can save a byte by using (repeatedly #(rand-int 2e9)) instead of (for[i(range)](rand-int 2e9)).

Whoops, I overlooked the fact that you're already inside a function literal; can't nest those...

I made an alternative approach! I'm not sure what the range is for the numbers supported, though...

This is not valid. Only outputting integers between 1 and 2e9 generates a finite sequence.

Python 2, 39 bytes
f=lambda l,s:sum({1/s//1}-l)or f(l,s/2)

Try it online!
Takes a list l of previous outputs (as a set) and a seed s that's a random real from 0 to 1.

The seed should be an integer.

@JonathanAllan I thought Mego OK'ed an infinite precision real in the comments. I'll confirm.

...also I think l should be defaulted to an empty container of some description.

If they did it's a game changer.

@JonathanAllan Reals are OK. I'm using the option that takes the previous integers as input.

That option states "as its sole argument" and "the first call may either take no arguments or take a seed argument".

@JonathanAllan I'm assuming the optional seed argument option is in addition to that. Otherwise, it's impossible to have any randomness for calls beyond the first. I'm waiting on a comment response about this.

@xnor I've clarified that.

Japt, 17 bytes
aA=(1/Mr)c)<0?A:ß

Try it online!

Clojure, 100 bytes
(fn[](let[a(atom[])](filter #(if-not(some #{%}@a)(swap! a conj %))(repeatedly #(bigint(/(rand)))))))

This function returns an infinite sequence of integers. To get the nth number of this series:
(nth (fn[]...) n)

To get the first n terms of this series:
(take n (fn[]...))

EDIT: Golfed 11 bytes (Thanks @NikoNyrh!) and added 3 bytes (changed int to bigint, to improve accuracy).

Nice option to hold the state, I got this approach down to 98 bytes by using if-not (dropping explicit false and true) and using unary version of /: #(int(/(rand))). Not sure if bigint would be more correct here as the result of that division might overflow int.

Java 8, 136 bytes
import java.util.*;()->{Set s=new HashSet();for(int n;;s.add(n))System.out.print(!s.contains(n=new Random().nextInt(-1>>>1))?n+";":"");}

Explanation:
Try it here. (Wait 60 seconds for the TIO to time-out to see the result.)
import java.util.*;     // Required import for the Set, HashSet, and Random

()->{                   // Method without parameters nor return-type
  Set s=new HashSet();  //  Set to keep track of numbers we've already outputted
 for(int n;;            //  Loop infinitely
     s.add(n))          //   And every time we output a random number, add it to the Set
   System.out.print(    //   Output:
    !s.contains(        //    If we haven't outputted it yet:
     n=new Random().nextInt(-1>>>1))?n+";"
                        //     A random number (range of int: 0 - 2³²)
    :                   //    Else:
     "");               //     Output nothing
}                       // End of method

JavaScript ES6, repeating call, 50 Bytes
c={0:9};f=_=>c[~~_]|Math.random()<.9?f(-~_):c[_]=_

JavaScript REPL, 48 bytes
for(o=[];;)o[n=1/Math.random()|0]||alert(o[n]=n)

APL, 33 bytes
∇P
S←⍬
→2/⍨S∊⍨X←⌊÷1-?0
S,←⎕←X
→2∇

Mathematica, 83 bytes
s=5;l={};t=1;While[t<30,If[l~FreeQ~s,Print@s];l~AppendTo~s;s=RandomInteger@100;t++]

starting with 5
Try it online!

The second program does not meet the specifications.

I agree with you, but the specifications are problematic themselves.there should be a bound otherwise you could expect any integer of any length

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Floor implementation
Target:
Write a floor() function from scratch.
Manipulating like converting float to string, and cutting all after dot are allowed.
All languages are allowed.
Any usage of built in language functions (like toInteger()) or similar is not allowed, casting operators are not allowed.
So, your task is implement floor() function without using casting and built in language functions.
Your function must support at least max 32-bit integer values (you will never receive negative values).
Forced casting (like somevar as float) and normal casting - such as(int) somevar -
 is not allowed, any built in functions, not allowed, all other stuff allowed.
Winner: Shortest implemention.

This is severely underspecified. 1. Which input range do we have to support. In particular, can the input be negative? 2. What exactly does built in language functions(like tointeger()) or something like this mean? I assume casting to integer is forbidden as well, but what about operations that simply return an integer (e.g., integer division by 1)? 3. C returns an integral floating point number, not an integer. Any hypothetical tointeger() would probably do something else.

@Dennis, sorry for underspecifies. I fix some problems of question

Casting is still unclear. Unless we are forced to return an integral float, we'll have to cast at some point. Also, does max int32 values refer to the maximal signed or the maximal unsigned integer? It might be clearer if you just state the limits in decimal.

@Dennis, fixed all

Can the result have a leading dot and zeroes (eg 5.67 -> 5.00)

C (gcc), 57 bytes
i;int f(float n){for(i=-2147483648;i<=n;i++);return i-1;}

Try it online! (it takes too long, so I changed it to start from 0.

I think you could save a byte by using 0x80000000 instead of -2147483648

Nice work.
It working and seems interesting.

You could also do i++<=n; instead

negative values not important, so is' default can be 0

You can remove the int return type from the function definition - the compiler will default to int if no other type is given.

1<<32-1 == -2147483648

Or even shorter: 5<<31

CJam, 6 bytes
q'.%0=

Try it online!
I found several 6 bytes solution but I can't do less than this.

"Manipulating like converting float to string, and cutting all after dot are allowed."

@LeakyNun "are allowed" means that I can do that, doesn't it?

Oops, I misread it...

"Any usage of built in language functions (like toInteger()) or similar is not allowed"

@monobogdan I haven't used any of those. I'm reading the input q, splitting where the point is '.% and taking the part before the point 0=

Javascript, 6 chars
x=>~~x

Test:

f = x=>~~x

document.addEventListener('input', event => {
  var x = event.target.valueAsNumber
  document.querySelector('output').textContent = x + " => " + f(x)
})
<input type=number> <output></output>

Batch, 53 bytes
@for /f "tokens=1 delims=." %%a in ("%1")do @echo %%a

Trims everything after .

Python 2, 21 13 bytes
lambda x:x//1

Outputs a float if input is float, outputs an integer if input is integer.
Try it online!

Japt, 2 bytes
|0

Try it online

Alternative
ÂU

Try it online

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Is this number triangular?
Challenge
Given a positive integer, determine whether it is a triangular number, and accordingly output one of any two constant, distinct values.
Definition
A triangular number is a number that can be expressed as the sum of consecutive positive integers, starting at 1. They can also be expressed with the formula \$\frac {n(n + 1)}  2\$, where \$n\$ is some positive integer.
Test cases
Truthy:
1
3
6
10
15
21
55
276
1540
2701
5050
7626
18915
71253
173166
222111
303031
307720
500500
998991

Falsy:
2
4
5
7
8
9
11
16
32
50
290
555
4576
31988
187394
501500
999999

Rules

Your entry may be a function or a program.
You may assume that the input is a positive integer under \$10^6\$.
You must pick two constant, distinct outputs to distinguish the two categories.

This is code-golf, so the shortest code in bytes in each language wins.

Related, related.

Related OEIS sequence

Related

Why didn't you include zero?

@Neil I wanted to minimize the number of possible edge cases, and handling zero is one of them that I felt wasn't too important. Do you think it would have been better if zero needed to be handled? (The Jelly answer currently fails on zero, for instance)

Bah, I would have thought programmers would have learned how to count starting at zero by now.

So, would an integer which is truthy in our language not count?

@RohanJhunjhunwala There is no requirement that your output values be truthy or falsy, but you can only have two of them.

Related

Related

Would this be a valid output for non-triangular numbers?

Is zero for truthy and non-zero for falsy/vice versa allowed?

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..]

Try it online!

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...

An imaginative method! You can save a byte with (!!)$show.(10^)=<<[0..].

Python, 24 bytes
lambda n:(8*n+1)**.5%1>0

Try it online!
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.

(1<<10000)**.5: OverflowError: int too large to convert to float

@isaacg The challenge doesn't require inputs that large: "You may assume that the input is a positive integer under 10^6"

@trichoplax I think I was disputing xnor's claim in the text. The submission is fine, I agree.

Python does not do arbitrary-precision exponentiation with ** unless both operands are integer. Otherwise it uses IEEE 374. This function reports both 6896076976160001 and its successor, 6896076976160002, as being triangular (that is the smallest number with which it fails).

@Deadcode Thanks, I stand corrected. I edited the post.

@Deadcode You mean 754? I don't see a 374.

@S.S.Anne My bad, it is IEEE 754. Don't know how I made a typo like that.

Jelly, 4 bytes
R+\ċ

Try it online!
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

I'm surprised cumulative reduce doesn't automatically make a range. Is there a design choice behind this?

I am not 100% sure, but I think it would (at least currently) need to by the dyadic operation being reduced over that would cause a range to be made.

...actually even that does not seem to apply (e.g. this vs this. It seems the quicklink implementation overrides such that the iterable does not make a range even if the dyadic operation defines it to do so for an argument. Pinged Dennis to field this one :)

@ETHproductions / and \ probably were among the first five quicks to be implemented, predating the idea to cast integer arguments to range.

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.

Why doesn't (^|1\1)+$ work?

@LeakyNun regex engines have an optimisation that they stop repeating a group if it was empty n times where n is the minimum of the quantifier you're using (in your case 1; if the minimum was 0, it would be tried once anyway). If you change the + to {2,}, it should work. This optimisation prevents infinite loops but it's also the only thing that keeps .NET regex from being Turing-complete on its own.

This just saved me 70 bytes: https://codegolf.stackexchange.com/a/118387

Make that 74 bytes, thanks to \G!

Python 2, 25 bytes
Checks if (8x+1) is a square number.
lambda x:(8*x+1)**.5%1==0

Try it online!

Mathematica, 16 bytes
OddQ@Sqrt[1+8#]&

Essentially a port of xnor's Python solution. Outputs True for triangular numbers, False otherwise.

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

Only seeing now that you edited the 19 byte solution into your answer a few minutes before I posted mine. Should I delete mine? What's the generally accepted etiquette on that?

@Shaggy I don't think it's a real problem here. My 'main' answer really is the recursive one.

Reduce to 28 bytes with f=(n,k=1)=>n>0?f(n-k,k+1):!n?

@kamoroso94 Thanks! Updated. And a third byte was saved by omitting the initialization of k.

Elegant use of bitwise NOT as an incrementor for an initially-undefined value; your edit was a pleasure to read after I independently arrived at your prior solution.

The second answer is sort of useless since its neither a program nor a function. Maybe if it were f=(x)=>... that adds 4 bytes.

@Octopus The 2nd answer is an arrow function. The usual practice is to omit f= (or whatever function name) unless it's referenced in the function itself, like in the first answer which is a recursive one.

I know what an arrow function is, but I don't understand your reasoning. If you can omit the f= then why not also omit the x=>. You still get the gist and it is still useless code. Don't you have to be able to use it as-is?

@Octopus Using unnamed functions is allowed (please see this meta answer). Omitting parameters is not. Or to put it in other words: the name of the function doesn't matter (you may even call it without naming it: (x=>(8*x+1)**.5%1==0)(15)) whereas the name of the parameters does matter (even if we can guess that it's x in a simple case like this one).

Okay, just trying to understand the rules. I was looking in meta for an answer.

@Octopus The rule as I've always understood is: if the challenge requires input, the submission must contain a mechanism for accepting input. this can either be done via arguments for a function submission or, if you choose not to use a function, by some explicit input mechanism like prompt (for JavaScript). What you can't do is say "assume this variable x has already been defined with the input..." -- it must either be that x is a formal argument whose value is provided when the function is called, or x must get its value explicitly in the code of the submission via user input.

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).
Try it online!
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.
}

CJam, 11 bytes
ri2*_mQ_)*=

Outputs 1 for triangular, 0 otherwise.
Try it online!
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

Jelly, 5 bytes
×8‘Æ²

Try it online!
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.

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 .

Try it online!

/ 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)/su drop subtraction, put input to bottom, shift left, swap counter and sum, increment counter, reflect, swap sum and counter, U-turn onto main loop body.

So tantalizingly close... that last byte is going to take a lot of effort and cleverness though.

Yep, thought I had it but is being elusive

@ETHproductions found the byte

Your code and your unfolded cube appear to be different, the lower right corner is a . on the cube but a 1 in your code.

@WheatWizard  Thanks for that, bad editing on my part

PowerShell, 31 30 bytes
"$args"-in(1..1e6|%{($s+=$_)})

Try it online!
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, 42 bytes
(([{}](<((())<>)>))<>){<>({}({}({})))}{}{}

Try it online!
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.
{(({}[()]))}(([[]])<>){({}{}())<>}({}{()<><{}>}{})

Try it online!

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

Try it online!

you can use ! instead of ==0

This is extra nice since it's vectorized, too!

I think you can get rid of the exterior brackets as well !(8*scan()+1)^.5%%1

MATL, 5 bytes
t:Ysm

Try it online!
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

I was going to post t:Ys=a. Forgot about m :-)

@LuisMendo I didn't know about m until I saw this answer. Funny how the two answer are almost identical :D

Japt, 10 7 bytes
Saved 3 bytes thanks to @Luke and @ETHproductions
*8Ä ¬v1

Try it online!
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?

Try it online!

The question asks for two constant distinct ouputs.

*8Ä ¬u1 c for 9B (outputs 0 if input is triangular, 1 otherwise)

@Luke You could change u1 c to v1, I believe (switching the outputs)

7 bytes? Nice! Somehow missed this while posting my own, similar solution late last might. Let me know if you'd like me to delete it.

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+...+$_).

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.
Try it online!
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

My first Alice answer

I have a feeling this could be roughly halved with one of Martin's fancy control structures...

So do I ... :-)

My first Alice golf: Same code, 23 bytes

A more "standard" layout for this kind of program would be this. That said, you could get rid of the 1 on the stack, and simply output the logical negation of the subtraction (i.e. ...h*-no@)

The simplest way to golf your current version by a lot is to move the o into the first line (simply write ...t/ o @). That already shortens it to 25. Doing the same for the i saves one more byte. (Of course, Leo's suggestion is still a fair bit shorter than that.)

@MartinEnder Thanks! If only characters had a square shape... :-)

@LuisMendo You can get 18 by using Leo's layout.

@Nitrodon You should post that as your answer :-)

@MartinEnder I think I'll leave that to him, as it's a significant change

@Leo Thanks for the tips. I'm not changing the layout, as it's a significant change. Feel free to post it yourself!

05AB1E, 7 6 bytes
EDIT: Thanks to @Dennis: Saved a byte because I forgot about the increment operator
8*>t.ï

Try it online!
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

Probably wasn't available yet at the time, but t.ï can be Å² these days, which is a builtin to check if a number is a square.

Brachylog, 5 bytes
≥ℕ⟦+?

Try it online!
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

05AB1E (legacy), 4 bytes
ÅTs¢

Try it online!
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

You can use 05AB1E rewrite for your answer as answers in languages newer than the challenge are now allowed.

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]

Try it at the TS playground
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.

PHP, 30 Bytes
Prints 1 for true and nothing for false

<?=fmod(sqrt(8*$argn+1),2)==1;

Try it online!
fmod
PHP, 37 Bytes
Prints 1 for true and nothing for false

<?=($x=sqrt($q=2*$argn)^0)*$x+$x==$q;

Try it online!

Mathematica, 28 bytes
!Accumulate@Range@#~FreeQ~#&

I recommend replacing 7! by #. First, it's shorter; more importantly, the current solution is not correct, as it artificially imposes a limit on the size of the input it works on.

OP says: "You may assume that the input is a positive integer under 10^6".But I like your idea and I will take it ,although mine gives the right result for every case using a list of 5040 elements but yours worst case needs a list of 999999 elements.Thanks for the tip!

Oops sorry, didn't see the OP's comment! Yes, there are some "perverse" incentives in code golfing: that 1-byte savings is more important in a code-golf question than all the efficiency in the world :)

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.

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>

I think you could save a byte with n=>(8*n+1)**.5%1>0 (which would reverse the outputs)

@ETHproductions: OK, as long as you're allowing it. Is doing so normally permitted, though?

It qualifies as "two constant, distinct outputs", so yes. Other decision-problem challenges may require truthy/falsy though.

Pari/GP, 18 bytes
n->issquare(8*n+1)

Try it online!

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)

Try it online!

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

=MOD(SQRT(8*A1+1),1)=0 saves a few bytes

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

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"

Try it online!
Test cases
Subtracts increasing numbers from the input until it reaches 0, and checks if the counter is zero.

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

Why not not(fPart(√(8Ans+1?

@lirtosiast That'll work, thanks!

APL (Dyalog), 6 bytes
⊢∊+\∘⍳

Try it online!
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.

Fourier, 26 bytes
I~X1(&N^*N/2{X}{1~O}N=X)Oo

Try it online!

Gol><>, 12 bytes
I8*P12,X1%zh

6 bytes golfed off, courtesy of JoKing! A codebreakdown will be coming soon!
Try it online!
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".
Try it online!

You can replace 1}:S(-Zh0h with 1%zh

A tip: You don't need to use conditionals like ?ZqQ for value checking. Just transform the values directly into 1 or 0 using comparison operators

@JoKing Thank you very much, I have made the changes and it has popped off 6 bytes!

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

A bit shorter counting downwards: TIO

@xnor oh wow, that is really clever

-1 because we don't need to handle zero.

C (gcc), 26 bytes
f(n){fmod(sqrt(8*n+1),1);}

Outputs zero for truthy and nonzero for falsy.
Try it online!

Why the downvote? If it's about the output format, I haven't gotten a response back from the OP on that.

Maybe the unspecified flags?

cQuents, 4 bytes
?Z+$

Try it online!
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)

Husk, 4 bytes
±£∫N

Try it online!
Since it reqiures a constant truthy value, ±(sign) is used.

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

Try it online!
^                  # 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

Try it online!
Doing so with NPCG-independent behavior costs 3 bytes, bringing it to 40 bytes:
^((((x*)x?)\3)x)(?=\4(\1*)\2*$)\1*$\5|^$

Try it online!
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

Try it online!
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

Try it online!
I haven't tried golfing this down yet. There may be specific golf optimizations for returning the triangular root.

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).

Fourier, 24 bytes
I~_(~#^*#/2{_}{1~$}#^)$o

Based on my other answer
Try it online!

Python 3, 105 bytes
import math
n=int(input(""))
if float(math.sqrt(8*n+1)).is_integer():
    print("y")
else:
    print("n")

Try it online!

Your answer can be a function, so it can be lambda n:float(math.sqrt(8*n+1)).is_integer();import math. And math.sqrt can be replaced with **0.5.

Desmos, 27 bytes
f(n)=0^{mod((8n+1)^{.5},1)}

Try It On Desmos!

dc, 18 bytes
Try it online!
?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

Welcome to Code Golf! Could you provide a link that shows the program on multiple inputs, like tio.run/#dc?

I added a tio link, but the program only takes one value at a time.

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

Welcome to Code Golf StackExchange, and nice first answer! I don't know TI-BASIC, but it seems that it has a special way to count bytes, so your answer might be shorter than 28 bytes.

Taking the input from a predefined variable is not allowed, but Ans is allowed

See the other ti-basic answer

Brain-Flak, 62 bytes
(([(({}))])<>){(({}())<>{}({})){(<><>)}{}<>}<>([[]]()()()<>{})

Try it online!
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

I ctrl-F'd for "><>"... Oh, there's already- no wait, that's Brain-Flak?

><>, 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.

If you move the +1 to the left of the < on the second line and start at n=0 instead of n=1, you can get rid of both of the spaces, like this.

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

C, 45 bytes
a,i;f(n){while(i<=n&&(a=i*i+i++!=2*n));a=!a;}

Try it online.
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.

CJam, 10
ri8*)_mQ%!

Try it online
It checks if 8*n+1 is divisible by its integer square root.

Interesting variant of the 8*n+1 method. In general this divisibility check tells if a number is of the form k^2, k^2+k or k^2+2*k, but a number of the form 8*n+1 can only be the first case.

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

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...

PowerShell, 36 bytes
for(;$args-gt$s){$s+=++$i}$s-in$args

Try it online!
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+$

Try it online!
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)

tinylisp, 65 60 bytes
(d T(q((N I)(i(l N 0)0(a(e N 0)(T(s N I)(a I 1)
(q((N)(T N 1

Try it online!

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)
Try it online!

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.

Nekomata + -e, 4 bytes
8*→√

Attempt This Online!
8*→√
8*    Multiply the input by 8
  →   Increment
   √  Check if it's a perfect square

Nekomata + -e, 4 bytes
R∫$Ĩ

Attempt This Online!
R∫$Ĩ
R     Range from 1 to input
 ∫    Cumulative sum
  $Ĩ  Check if it contains the input

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)

Attempt This Online!

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])

Uiua, 14 bytes SBCS
Outputs 0 for false and 1 for true. Uses the "8n+1 is Perfect Square" method.
&p=⌊.√+1×8⋕&sc

Try it online!
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

Uiua, 6 bytes
∊:\+⇡.

Try it
Is the input a member of taking the cumulative sums of the range of 0 to the input?

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

The 8x+1 trick is actually longer: b=sqr(8*:+1)?b=int(b)

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 %)))

Japt, 11 9 7 bytes
Port of my JS answer. Outputs 1 for triangular numbers or 0 otherwise.
*8Ä ¬v1

Try it online

C (gcc), 47 bytes
a,i;f(n){for(a=i=0;i++<n+3;)a|=i*i==8*n+1;a=a;}

Try it online!
Undefined behaviour?

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)).
Try it here.

Why Math.pow instead of Math.sqrt?

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

Try it!

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

I tried to create a TIO, but I couldn't figure out how to get function arguments to pass it within 5 minutes of trying. I'll try to add one later when I have more time.

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.
Try it online!

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.

cQuents, 7 6 bytes
?b$
;$

Try it online!
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.

JavaScript (ES8), 21 bytes
a=n=>!((8*n+1)**.5%1)

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 (=<.)

0=1|2!inv does something like this. 0=1|2&!inv for a proper function.

@FrownyFrog Cool! That's real clever

05AB1E, 4 bytes
ÅTI¢

Try it online!
Explanation:
ÅT     Get list of triangle numbers less than or equal to the implicit input
  I¢   Count occurrences of input in list

In this case the count will give exactly the same output, but just a FYI: there is also a contains builtin: å. :) (PS: There is already an 05AB1E answer using the same approach.)

Desmoslang, 24 Bytes
0^{\mod((8*I+1)^{.5},1OT

Perl 5 -p, 21 bytes
$_=sqrt(1+8*$_)!~/\./

Try it online!

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/