34
\$\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 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 106.
  • 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\$
  • 1
    \$\begingroup\$ Related, related. \$\endgroup\$ – ETHproductions May 22 '17 at 20:27
  • \$\begingroup\$ Related OEIS sequence \$\endgroup\$ – ovs May 22 '17 at 21:14
  • \$\begingroup\$ Related \$\endgroup\$ – Shaggy May 22 '17 at 21:28
  • \$\begingroup\$ Why didn't you include zero? \$\endgroup\$ – Neil May 22 '17 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\$ – ETHproductions May 22 '17 at 21:44

58 Answers 58

1
2
2
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Why not not(fPart(√(8Ans+1? \$\endgroup\$ – lirtosiast Aug 25 '17 at 0:48
  • \$\begingroup\$ @lirtosiast That'll work, thanks! \$\endgroup\$ – Scott Milner Aug 25 '17 at 2:59
2
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

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!

Triangular Number 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!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You can replace 1}:S(-Zh0h with 1%zh \$\endgroup\$ – Jo King Feb 14 '19 at 4:45
  • \$\begingroup\$ 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 \$\endgroup\$ – Jo King Feb 14 '19 at 5:07
  • \$\begingroup\$ @JoKing Thank you very much, I have made the changes and it has popped off 6 bytes! \$\endgroup\$ – KrystosTheOverlord Feb 14 '19 at 12:10
1
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ I ctrl-F'd for "><>"... Oh, there's already- no wait, that's Brain-Flak? \$\endgroup\$ – Esolanging Fruit May 23 '17 at 6:14
1
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Not a tree May 23 '17 at 9:27
1
\$\begingroup\$

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

CJam, 10

ri8*)_mQ%!

Try it online

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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Ørjan Johansen Oct 26 '17 at 19:30
1
\$\begingroup\$

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

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)
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ A bit shorter counting downwards: TIO \$\endgroup\$ – xnor Mar 19 at 23:50
  • \$\begingroup\$ @xnor oh wow, that is really clever \$\endgroup\$ – RGS Mar 20 at 9:05
  • 1
    \$\begingroup\$ -1 because we don't need to handle zero. \$\endgroup\$ – Bubbler Apr 6 at 2:30
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
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ The 8x+1 trick is actually longer: b=sqr(8*:+1)?b=int(b) \$\endgroup\$ – steenbergh May 23 '17 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 %)))
| improve this answer | |
\$\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?

| improve this answer | |
\$\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!

| improve this answer | |
\$\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
| improve this answer | |
\$\endgroup\$
  • \$\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 May 23 '17 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!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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. 
| improve this answer | |
\$\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.

| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
  • 3
    \$\begingroup\$ Why Math.pow instead of Math.sqrt? \$\endgroup\$ – JollyJoker May 23 '17 at 13:26
0
\$\begingroup\$

JavaScript (ES8), 21 bytes

a=n=>!((8*n+1)**.5%1)
| improve this answer | |
\$\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

| improve this answer | |
\$\endgroup\$
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 (=<.)

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 0=1|2!inv does something like this. 0=1|2&!inv for a proper function. \$\endgroup\$ – FrownyFrog Jan 11 '18 at 4:39
  • \$\begingroup\$ @FrownyFrog Cool! That's real clever \$\endgroup\$ – Bolce Bussiere Jan 11 '18 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.
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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

| improve this answer | |
\$\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
| improve this answer | |
\$\endgroup\$
  • \$\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\$ – Kevin Cruijssen Mar 13 '19 at 11:54
0
\$\begingroup\$

C (gcc), 26 bytes

f(n){fmod(sqrt(8*n+1),1);}

Outputs zero for truthy and nonzero for falsy.

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Why the downvote? If it's about the output format, I haven't gotten a response back from the OP on that. \$\endgroup\$ – S.S. Anne Mar 28 at 23:57
0
\$\begingroup\$

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)
| improve this answer | |
\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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