85
\$\begingroup\$

I'm honestly surprised that this hasn't been done already. If you can find an existing thread, by all means mark this as a duplicate or let me know.

Input

Your input is in the form of any positive integer greater than or equal to 1.

Output

You must output the sum of all integers between and including 1 and the number input.

Example

 In: 5
     1+2+3+4+5 = 15
Out: 15

OEIS A000217 — Triangular numbers: a(n) = binomial(n+1,2) = n(n+1)/2 = 0 + 1 + 2 + ... + n.

Leaderboard

Run the code snippet below to view a leaderboard for this question's answers. (Thanks to programmer5000 and steenbergh for suggesting this, and Martin Ender for creating it.)

var QUESTION_ID=133109,OVERRIDE_USER=69148;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
10
  • 5
    \$\begingroup\$ Closely related \$\endgroup\$ Commented Jul 18, 2017 at 20:36
  • \$\begingroup\$ @FryAmTheEggman Sorry - had a bit of a brain fart there. I see what you mean. \$\endgroup\$
    – Gareth
    Commented Jul 18, 2017 at 20:45
  • 2
    \$\begingroup\$ @Aaron you got ninja'd by Husk, which was just posted with a 1 byte solution \$\endgroup\$
    – Mayube
    Commented Jul 18, 2017 at 21:35
  • 7
    \$\begingroup\$ I suggest a stack snippet. \$\endgroup\$
    – user58826
    Commented Jul 19, 2017 at 11:42
  • 1
    \$\begingroup\$ Related: minecraftforum.net/forums/off-topic/… \$\endgroup\$ Commented Jul 27, 2017 at 12:20

222 Answers 222

1
2 3 4 5
8
51
\$\begingroup\$

Pyth, 2 bytes

sS

Try it online! Implicit input. S is 1-indexed range, and s is the sum.

\$\endgroup\$
3
  • 119
    \$\begingroup\$ Finally, Pyth(on) code sounds like a snake. \$\endgroup\$ Commented Jul 18, 2017 at 21:15
  • 2
    \$\begingroup\$ This is the perfect challenge for Pyth... \$\endgroup\$
    – Mr. Xcoder
    Commented Jul 18, 2017 at 22:09
  • \$\begingroup\$ I was going to answer this, but I guess not \$\endgroup\$
    – Stan Strum
    Commented Sep 7, 2017 at 3:41
37
\$\begingroup\$

Husk, 1 byte

Σ

Try it online!

Builtin! Σ in Husk is usually used to get the sum of all elements of a list, but when applied to a number it returns exactly n*(n+1)/2.

\$\endgroup\$
4
  • 2
    \$\begingroup\$ Out of curiosity, does this occur because the number is cast to a range and then summed, or is this actually hardcoded? \$\endgroup\$ Commented Jul 18, 2017 at 21:33
  • 7
    \$\begingroup\$ @FryAmTheEggman this is actually hardcoded, and is similar to the behavior of another builtin, Π, which can compute the product of all elements of a list or the factorial of a single number \$\endgroup\$
    – Leo
    Commented Jul 18, 2017 at 21:37
  • 6
    \$\begingroup\$ Σ is a two byte unicode character on my machine. I guess you use code page 1253? msdn.microsoft.com/en-us/library/cc195055.aspx \$\endgroup\$
    – gmatht
    Commented Jul 19, 2017 at 2:32
  • 7
    \$\begingroup\$ @gmatht Husk's code page \$\endgroup\$ Commented Jul 19, 2017 at 3:02
26
\$\begingroup\$

Piet, 161 bytes / 16 codels

You can interpret it with this Piet interpreter or upload the image on this website and run it there. Not sure about the byte count, if I could encode it differently to reduce size.

Scaled up version of the source image:

rapapaing-image

Explanation

The highlighted text shows the current stack (growing from left to right), assuming the user input is 5:

1st transition Input a number and push it onto stack

5

2nd transition Duplicate this number on the stack

5 5

3rd transition Push 1 (the size of the dark red area) onto stack

5 5 1

4th transition Add the top two numbers

5 6

5th transition Multiply the top two numbers

30

6th transition The black area makes sure, that the cursor moves down right to the light green codel. That transition pushes 2 (the size of dark green) onto stack

30 2

7th transition Divide the second number on the stack by the first one

15

8th transition Pop and output the top number (interpreted as number)

[empty]

final trap By inserting a white area, the transition is a nop, the black traps our cursor. This ends execution of the program.

Original file (far too small for here): Original source image

\$\endgroup\$
3
  • 2
    \$\begingroup\$ We transitioned from an intelligible text (e.g. C) to unintelligible text (e.g. Jelly) to images... What next? :P \$\endgroup\$
    – frarugi87
    Commented Jul 24, 2017 at 7:32
  • 2
    \$\begingroup\$ +1 I haven't actually seen a Piet answer with an explanation before \$\endgroup\$
    – MilkyWay90
    Commented Apr 1, 2019 at 23:01
  • 1
    \$\begingroup\$ How did you get 16 for the number of codels? I count 33 (11 by 3), and even just counting the codels that "do something," I can't make it come out to 16. (It's not a super important question since you're scoring the solution in bytes, but I found it puzzling.) \$\endgroup\$
    – DLosc
    Commented Jul 25, 2022 at 17:50
25
\$\begingroup\$

Brain-Flak, 16 bytes

({({}[()])()}{})

Try it online!

This is one of the few things that brain-flak is really good at.

Since this is one of the simplest things you can do in brain-flak and it has a lot of visibility, here's a detailed explanation:

# Push the sum of all of this code. In brain-flak, every snippet also returns a
# value, and all values inside the same brackets are summed
(
    # Loop and accumulate. Initially, this snippet return 0, but each time the
    # loop runs, the value of the code inside the loop is added to the result.
    {
        # Push (and also return)...
        (
            # The value on top of the stack
            {}

            # Plus the negative of...
            [
                # 1
                ()
            ]

        # The previous code pushes n-1 on to the stack and returns the value n-1
        )

        # 1
        # This code has no side effect, it just returns the value 1 each loop.
        # This effectively adds 1 to the accumulator
        ()

    # The loop will end once the value on top of the stack is 0
    }

    # Pop the zero off, which will also add 0 to the current value
    {}

# After the sum is pushed, the entire stack (which only contains the sum)
# will be implicitly printed.
)
\$\endgroup\$
24
\$\begingroup\$

Oasis, 3 bytes

n+0

Try it online!

How it works

n+0
  0    a(0)=0
n+     a(n)=n+a(n-1)
\$\endgroup\$
1
  • 40
    \$\begingroup\$ And here I was, all of my life thinking that n+0 is n... \$\endgroup\$
    – Wojowu
    Commented Jul 19, 2017 at 7:22
20
\$\begingroup\$

JavaScript (ES6), 10 bytes

n=>n*++n/2

Example

let f =

n=>n*++n/2

console.log(f(5))

\$\endgroup\$
1
  • 5
    \$\begingroup\$ n*-~n/2 also works, but only for n < 2**31 \$\endgroup\$ Commented Dec 3, 2017 at 18:53
19
\$\begingroup\$

Mathematica, 9 bytes

#(#+1)/2&

Mathematica, 10 bytes

(#^2+#)/2&

Mathematica, 11 bytes

Tr@Range@#&

Mathematica, 12 bytes

i~Sum~{i,#}&

Mathematica, 14 bytes

(by @user71546)

1/2/Beta[#,2]&

Mathematica, 15 bytes

Tr[#&~Array~#]&

Mathematica, 16 bytes

Binomial[#+1,2]&

Mathematica, 17 bytes

(by @Not a tree)

⌊(2#+1)^2/8⌋&

Mathematica, 18 bytes

PolygonalNumber@#&

Mathematica, 19 bytes

#+#2&~Fold~Range@#&

Mathematica, 20 bytes

(by @Not a tree)

f@0=0;f@i_:=i+f[i-1]
\$\endgroup\$
13
  • 5
    \$\begingroup\$ It seems a shame to skip 13, 14 and 17… \$\endgroup\$
    – Not a tree
    Commented Jul 19, 2017 at 0:48
  • 3
    \$\begingroup\$ It seems like a next challenge....or at least help me to complete the list. \$\endgroup\$
    – ZaMoC
    Commented Jul 19, 2017 at 0:51
  • 2
    \$\begingroup\$ I still don't have anything for 13 or 14 bytes (apart from just un-golfing your shorter answers), but here are another 26 with larger byte-counts. \$\endgroup\$
    – Not a tree
    Commented Jul 19, 2017 at 7:16
  • 1
    \$\begingroup\$ @MarkS. on 10.4 works fine \$\endgroup\$
    – ZaMoC
    Commented Jul 25, 2017 at 10:56
  • 1
    \$\begingroup\$ @Notatree For your list, here is a candidate for 35: Array[Boole[#2>=#]&,{#,#}]~Total~2& \$\endgroup\$
    – Mark S.
    Commented Aug 12, 2017 at 5:07
12
\$\begingroup\$

Python 2, 24 16 bytes

-8 bytes thanks to FryAmTheEggman.

lambda n:n*-~n/2

Try it online!

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

x86_64 machine language (Linux), 9 8 bytes

0:   8d 47 01                lea    0x1(%rdi),%eax
3:   f7 ef                   imul   %edi
5:   d1 e8                   shr    %eax
7:   c3                      retq 

To Try it online! compile and run the following C program.

#include<stdio.h>
const char f[]="\x8d\x47\x01\xf7\xef\xd1\xe8\xc3";
int main(){
  for( int i = 1; i<=10; i++ ) {
    printf( "%d %d\n", i, ((int(*)())f)(i) );
  }
}

Thanks to @CodyGray and @Peter for -1.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ You should probably use shr instead of sar, to treat your output as unsigned (no change in code size). (Spotted by @CodyGray and pointed out in his 7-byte add+loop answer). \$\endgroup\$ Commented Jul 22, 2017 at 8:36
  • 2
    \$\begingroup\$ This looks optimal for performance in an implementation of the closed-form formula, but you can save a byte by using the one-operand form of mul %edi or imul %edi (each 2B) instead of the 3B two-operand form. It clobbers EDX with the high-half result, but that's fine. Multi-operand imul was introduced later than the one-operand form, and has a 2-byte opcode with a 0F escape byte. Any of the three options will always produce the same result in eax, it's only the high half that depends on signed vs. unsigned. \$\endgroup\$ Commented Jul 22, 2017 at 8:36
11
\$\begingroup\$

C# (.NET Core), 10 bytes

n=>n++*n/2

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Polyglots with JS. \$\endgroup\$
    – Makonede
    Commented Apr 19, 2021 at 20:41
10
\$\begingroup\$

Java (OpenJDK 8), 10 bytes

n->n++*n/2

Try it online!

\$\endgroup\$
10
\$\begingroup\$

Jelly, 2 bytes

RS

Try it online!

Explanation

RS

    implicit input
 S  sum of the...
R   inclusive range [1..input]
    implicit output

Gauss sum, 3 bytes

‘×H

Explanation

‘×H

     implicit input
  H  half of the quantity of...
‘    input + 1...
 ×   times input
     implicit output
\$\endgroup\$
1
  • \$\begingroup\$ This also works in Anyfix :P (not on TIO) \$\endgroup\$
    – hyperneutrino
    Commented Jul 18, 2017 at 21:08
10
\$\begingroup\$

Octave, 22 19 bytes

Because arithmetic operations are boring...

@(n)nnz(triu(e(n)))

Try it online!

Explanation

Given n, this creates an n×n matrix with all entries equal to the number e; makes entries below the diagonal zero; and outputs the number of nonzero values.

\$\endgroup\$
3
  • \$\begingroup\$ Is this actually shorter than the numerical version? \$\endgroup\$ Commented Jul 23, 2017 at 15:26
  • \$\begingroup\$ @Challenger5 No, But the numerical version is boring: @(n)sum(1:n) \$\endgroup\$
    – Luis Mendo
    Commented Jul 23, 2017 at 15:52
  • 2
    \$\begingroup\$ Or 16 bytes with arithmetic operations, but no sum. \$\endgroup\$ Commented Aug 6, 2017 at 17:35
9
\$\begingroup\$

Haskell, 13 bytes

This is the shortest (I thinkthought):

f n=sum[1..n]

Try it online!

Direct, 17 13 bytes

f n=n*(n+1)/2

Thanks @WheatWizard for -4 bytes!

Try it online!

Pointfree direct, 15 bytes

(*)=<<(/2).(+1)

Thanks @nimi for the idea!

Try it online!

Pointfree via sum, 16 bytes

sum.enumFromTo 1

Try it online!

Recursively, 22 18 bytes

f 0=0;f n=n+f(n-1)

Thanks @maple_shaft for the idea & @Laikoni for golfing it!

Try it online!

Standard fold, 19 bytes

f n=foldr(+)0[1..n]

Try it online!

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

Java (OpenJDK 8), 10 bytes

a->a++*a/2

Try it online!

Took a moment to golf down from n->n*(n+1)/2 because I'm slow.

But this isn't a real Java answer. It's definitely not verbose enough.

import java.util.stream.*;
a->IntStream.range(1,a+1).sum()

Not bad, but we can do better.

import java.util.stream.*;
(Integer a)->Stream.iterate(1,(Integer b)->Math.incrementExact(b)).limit(a).reduce(0,Integer::sum)

I love Java.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ If you want it to be even more verbose why use a lambda!? :P \$\endgroup\$ Commented Jul 19, 2017 at 12:36
  • 2
    \$\begingroup\$ I was aiming for verbose lambdas, I could write a full program if I wanted to be particularly eloquent :P \$\endgroup\$
    – Xanderhall
    Commented Jul 19, 2017 at 12:38
  • 1
    \$\begingroup\$ The exact same solution was already posted \$\endgroup\$
    – Winter
    Commented Jul 19, 2017 at 18:56
  • 2
    \$\begingroup\$ I must have missed it, but in any case, I tend to not look at the contents of other answers. I prefer to write my own golf. \$\endgroup\$
    – Xanderhall
    Commented Jul 20, 2017 at 11:21
8
\$\begingroup\$

APL, 3 bytes

+/⍳

Try it online!

+/ - sum (reduce +), - range.

\$\endgroup\$
2
  • \$\begingroup\$ This depends on the indexing. If indexing is set to 0, then you'd need an additional 2 bytes 1+ \$\endgroup\$
    – Werner
    Commented Jul 18, 2017 at 21:27
  • 2
    \$\begingroup\$ @Werner indexing is default 1 so I didn't specify. its common here to specify only when using ⎕IO←0 (and it does not included in byte count) \$\endgroup\$
    – Uriel
    Commented Jul 18, 2017 at 21:29
8
\$\begingroup\$

Taxi, 687 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l 2 r.[a]Pickup a passenger going to Addition Alley.Pickup a passenger going to The Underground.Go to Zoom Zoom:n.Go to Addition Alley:w 1 l 1 r.Pickup a passenger going to Addition Alley.Go to The Underground:n 1 r 1 r.Switch to plan "z" if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 3 l 2 l.Switch to plan "a".[z]Go to Addition Alley:n 3 l 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

Try it online!

Un-golfed with comments:

[ n = STDIN ]
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left 1st left 2nd right.

[ for (i=n;i>1;i--) { T+=i } ]
[a]
Pickup a passenger going to Addition Alley.
Pickup a passenger going to The Underground.
Go to Zoom Zoom: north.
Go to Addition Alley: west 1st left 1st right.
Pickup a passenger going to Addition Alley.
Go to The Underground: north 1st right 1st right.
Switch to plan "z" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 3rd left 2nd left.
Switch to plan "a".

[ print(T) ]
[z]
Go to Addition Alley: north 3rd left 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: north 1st right 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.

It's 22.6% less bytes to loop than it is to use x*(x+1)/2

\$\endgroup\$
7
\$\begingroup\$

Julia, 10 bytes

n->n*-~n/2

Try it online!

11 bytes (works also on Julia 0.4)

n->sum(1:n)

Try it online!

\$\endgroup\$
7
\$\begingroup\$

Starry, 27 22 bytes

5 bytes saved thanks to @miles!

, + +  **       +   *.

Try it online!

Explanation

,             Read number (n) from STDIN and push it to the stack
 +            Duplicate top of the stack
 +            Duplicate top of the stack
  *           Pop two numbers and push their product (n*n)
*             Pop two numbers and push their sum (n+n*n)
       +      Push 2
   *          Pop two numbers and push their division ((n+n*n)/2)
.             Pop a number and print it to STDOUT
\$\endgroup\$
2
  • \$\begingroup\$ 22 bytes. \$\endgroup\$
    – miles
    Commented Jul 18, 2017 at 23:20
  • \$\begingroup\$ @miles Thanks! Very good idea! \$\endgroup\$
    – Luis Mendo
    Commented Jul 18, 2017 at 23:53
7
\$\begingroup\$

05AB1E, 2 bytes

LO

Try it online!

How it works

     #input enters stack implicitly
L    #pop a, push list [1 .. a]
 O   #sum of the list
     #implicit output 

Gauss sum, 4 bytes

>¹*;

Try it online!

How it works

>       #input + 1
 ¹*     #get original input & multiply
   ;    #divide by two 
\$\endgroup\$
3
  • 3
    \$\begingroup\$ ÝO also works and means hello. \$\endgroup\$ Commented Jul 19, 2017 at 15:01
  • 2
    \$\begingroup\$ L0 and behold.. \$\endgroup\$
    – dylnan
    Commented Dec 11, 2017 at 16:16
  • \$\begingroup\$ The Gaussian sum can be shortened by one byte without ¹, as implicit input can be reused. \$\endgroup\$
    – Makonede
    Commented Apr 19, 2021 at 20:37
7
\$\begingroup\$

Check, 5 bytes

:)*$p

Check isn't even a golfing language, yet it beats CJam!

Try it online!

Explanation:

The input number is placed on the stack. : duplicates it to give n, n. It is then incremented with ), giving n, n+1. * multiplies the two together, and then $ divides the result by 2. p prints the result and the program terminates.

\$\endgroup\$
7
\$\begingroup\$

Piet + ascii-piet, 16 bytes (4×4=16 codels)

tabR   Smm Amtqa

Try Piet online!

How it works

The code simply follows the border and then stops at the 3-cell L-shaped region. Basically uses the well-known formula, because setting up a loop here costs too many cells due to the necessary roll command.

Command    Stack
inN        [n]
dup 1 +    [n n+1]
* 2 /      [n*(n+1)/2]
outN       []

This layout saves two black cells over the following linear, more straightforward (pun intended) layout:

Piet + ascii-piet, 18 bytes (2×9=18 codels)

tabrsaqtM     a mm

Try Piet online!

\$\endgroup\$
6
\$\begingroup\$

MATL, 2 bytes

:s

Try it online!

Not happy smiley.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Damn it, finally a challenge I could easily answer in MATL, but you beat me to it :( \$\endgroup\$
    – Lui
    Commented Jul 19, 2017 at 6:27
6
\$\begingroup\$

dc, 7 bytes

d1+*2/p

OR

d2^+2/p

OR

dd*+2/p

Try it online!

\$\endgroup\$
5
\$\begingroup\$

Brainfuck, 24 Bytes.

I/O is handled as bytes.

,[[->+>+<<]>[-<+>]<-]>>.

Explained

,[[->+>+<<]>[-<+>]<-]>>.
,                           # Read a byte from STDIN
 [                  ]       # Main loop, counting down all values from n to 1
  [->+>+<<]                 # Copy the i value to *i+1 and *i+2
           >[-<+>]          # Move *i+1 back to i
                  <-        # Move back to i, lower it by one. Because *i+2 is never reset, each iteration adds the value of i to it.
                     >>.    # Output the value of *i+2
\$\endgroup\$
4
  • 2
    \$\begingroup\$ It's pretty cool that Brainfuck is able to beat some higher-level languages in this challenge. \$\endgroup\$
    – Gareth
    Commented Jul 19, 2017 at 10:49
  • \$\begingroup\$ Is that legit for me to add an answer in Lenguage (just for fun) using your code? @ATaco \$\endgroup\$ Commented Jul 26, 2017 at 12:44
  • \$\begingroup\$ I don't think so, as it would be the same code, just encoded different. @V.Courtois \$\endgroup\$
    – ATaco
    Commented Jul 26, 2017 at 13:07
  • \$\begingroup\$ @ATaco Ahh you're right. \$\endgroup\$ Commented Jul 26, 2017 at 13:19
5
\$\begingroup\$

C++ (template metaprogramming), 80 bytes (?)

I'm not very sure if it is acceptable because you need to insert input into source, which seems to be permitted for languages like /// only.

template<int N>struct s{enum{v=N+s<N-1>::v};};template<>struct s<1>{enum{v=1};};

Example:

#include <iostream>
int main()
{
    std::cout<<s<10>::v;
    return 0;
}
\$\endgroup\$
5
\$\begingroup\$

,,,, 6 bytes

:1+×2÷

Explanation

:1+×2÷

:       ### duplicate
 1+     ### add 1
   ×    ### multiply
    2÷  ### divide by 2

If I implement range any time soon...

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

Bash, 13 bytes

seq -s+ $1|bc

Try it online!

seq generates a sequence. seq 5 generates a sequence of numbers from 1 to 5 with a default increment of 1.

seq with the -s flag uses a string parameter to separate the numbers (the default separator is \n).

So seq -s+ $1 generates numbers from 1 to $1, the first argument, using + as the separator. With an argument of 5, this generates 1+2+3+4+5.

Now this is piped into bc using |bc to calculate the result of this mathematical expression and that value it outputted.

\$\endgroup\$
5
\$\begingroup\$

Retina 0.8.2, 13 bytes

.+
$*
1
$`1
1

Try it online! Explanation: The first and last stages are just unary ⇔ decimal conversion. The middle stage replaces each 1 with the number of 1s to its left plus another 1 for the 1 itself, thus counting from 1 to n, summing the values implicitly.

\$\endgroup\$
4
  • \$\begingroup\$ Beaten by 4 bytes in Retina 1.0. \$\endgroup\$
    – Deadcode
    Commented Jul 22, 2022 at 18:08
  • \$\begingroup\$ @Deadcode Yeah, Retina 0.8.2 (which this answer is in, since Retina 1 didn't exist at the time) doesn't have an equivalent to Retina 1's w flag. Nice approach though! \$\endgroup\$
    – Neil
    Commented Jul 22, 2022 at 18:59
  • \$\begingroup\$ I know, that's why I included the version number in my comment. And thanks. \$\endgroup\$
    – Deadcode
    Commented Jul 22, 2022 at 19:05
  • \$\begingroup\$ Replacing 1 with $'1 or 1? with $` also works for the same byte count. Replacing 1 with $` or $' results in binomial(n,2). \$\endgroup\$
    – Neil
    Commented Jul 24, 2022 at 8:51
5
\$\begingroup\$

Trilangle, 9 bytes

How appropriate that the triangular language is computing triangular numbers.

?2')2!*:@

Try it on the online interpreter!

Unwraps to this triangular grid:

   ?
  2 '
 ) 2 !
* : @ .

Instructions are executed in this order:

  • ?: Read an integer from STDIN
  • 2: Duplicate the top of the stack
  • ): Increment the top of the stack
  • *: Multiply the two values off the top of the stack
  • '2: Push the number 2 to the stack
  • :: Divide the two values off the top of the stack
  • !: Print the top of the stack as a decimal number
  • @: Terminate program.

Effectively identical to this C program:

#include <stdio.h>

int main() {
  // ?
  int i; while(!scanf("%i", &i)) getchar();

  // 2)*
  i *= i + 1;

  // '2:
  i /= 2;

  // !
  printf("%d\n", i);

  // @
  return 0;
}
\$\endgroup\$
1
2 3 4 5
8

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.