45
\$\begingroup\$

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.

\$\endgroup\$
12
  • 1
    \$\begingroup\$ Related, related. \$\endgroup\$ Commented May 22, 2017 at 20:27
  • \$\begingroup\$ Related OEIS sequence \$\endgroup\$
    – ovs
    Commented May 22, 2017 at 21:14
  • \$\begingroup\$ Related \$\endgroup\$
    – Shaggy
    Commented May 22, 2017 at 21:28
  • \$\begingroup\$ Why didn't you include zero? \$\endgroup\$
    – Neil
    Commented May 22, 2017 at 21:40
  • 2
    \$\begingroup\$ @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) \$\endgroup\$ Commented May 22, 2017 at 21:44

77 Answers 77

1 2
3
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Uiua, 6 bytes

∊:\+⇡.

Try it

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

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ The 8x+1 trick is actually longer: b=sqr(8*:+1)?b=int(b) \$\endgroup\$
    – steenbergh
    Commented May 23, 2017 at 9:25
0
\$\begingroup\$

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 %)))
\$\endgroup\$
0
\$\begingroup\$

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?

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – Brian J
    Commented May 23, 2017 at 13:31
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
1
  • 4
    \$\begingroup\$ Why Math.pow instead of Math.sqrt? \$\endgroup\$
    – JollyJoker
    Commented May 23, 2017 at 13:26
0
\$\begingroup\$

JavaScript (ES8), 21 bytes

a=n=>!((8*n+1)**.5%1)
\$\endgroup\$
0
\$\begingroup\$

Japt, 11 9 7 bytes

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

*8Ä ¬v1

Try it online

\$\endgroup\$
0
0
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ 0=1|2!inv does something like this. 0=1|2&!inv for a proper function. \$\endgroup\$
    – FrownyFrog
    Commented Jan 11, 2018 at 4:39
  • \$\begingroup\$ @FrownyFrog Cool! That's real clever \$\endgroup\$ Commented Jan 11, 2018 at 5:20
0
\$\begingroup\$

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.
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ 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.) \$\endgroup\$ Commented Mar 13, 2019 at 11:54
0
\$\begingroup\$

Desmoslang, 24 Bytes

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

Perl 5 -p, 21 bytes

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

Try it online!

\$\endgroup\$
1 2
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.