# 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 , so the shortest code in bytes in each language wins.

• May 22, 2017 at 20:27
• Related OEIS sequence
– ovs
May 22, 2017 at 21:14
• Related May 22, 2017 at 21:28
• Why didn't you include zero?
– Neil
May 22, 2017 at 21:40
• @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) May 22, 2017 at 21:44

# 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) May 23, 2017 at 9:25

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


# 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?

# 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. May 23, 2017 at 13:31

# 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
dup
dup
push 1
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.

# Java 8, 5848 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? May 23, 2017 at 13:26

# JavaScript (ES8), 21 bytes

a=n=>!((8*n+1)**.5%1)


# Japt, 119 7 bytes

Port of my JS answer. Outputs 1 for triangular numbers or 0 otherwise.

*8Ä ¬v1


Try it online

# 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. Jan 11, 2018 at 4:39
• @FrownyFrog Cool! That's real clever Jan 11, 2018 at 5:20

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


# 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.) Mar 13, 2019 at 11:54

# Desmoslang, 24 Bytes

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


# Perl 5-p, 21 bytes

$_=sqrt(1+8*$_)!~/\./


Try it online!