# Sum of all integers from 1 to n

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>

• Closely related Jul 18, 2017 at 20:36
• @FryAmTheEggman Sorry - had a bit of a brain fart there. I see what you mean. Jul 18, 2017 at 20:45
• @Aaron you got ninja'd by Husk, which was just posted with a 1 byte solution Jul 18, 2017 at 21:35
• I suggest a stack snippet.
– user58826
Jul 19, 2017 at 11:42
• Jul 27, 2017 at 12:20

# R, 13 bytes

sum(1:scan())


Saved 9 bytes thanks to Giuseppe and Max Lawnboy.

• Would be shorter if you used n=scan() instead of defining a function. Jul 19, 2017 at 2:22
• And it would be even shorter to just use sum(1:scan()) Jul 19, 2017 at 2:47
• This is not a valid R code. I believe this is what you were aiming at f=function(n)sum(1:n). Jul 19, 2017 at 9:50
• ^ You're right, I think when I removed the spaces I was too quick as I did run it in R and just c/p'ed it over. Jul 19, 2017 at 10:42
• It should be sum(1:scan()), not sum(1:scan(n)). Jul 19, 2017 at 20:59

# Forth, 17 bytes

Defines a word (function) that returns n*(n+1)/2.

: f dup 1+ * 2/ ;


Try it online

Full program with the same byte count:

key dup 1+ * 2/ .


Try it online - input is a single character, like BF.

# C, 22 bytes

With preprocessor

#define F(n) (n+1)*n/2


or 24 bytes with code and math

F(n){return (n+1)*n/2;}


or 27 bytes with recursive code

F(n){return n?n+F(n-1):0;}

• eliminate spaces: #define F(N)(n+1)*n/2, F(N){return(n+1)*n/2}; Jul 18, 2017 at 23:13
• And for the "code and math" section, you don't need the semicolon after the }. Jul 19, 2017 at 17:23
• Um ... actually the first two solutions don't work... C is case sensitive! Jul 23, 2017 at 16:18
• also change (n+1) to -~n: #define F(n)-~n*n/2 Oct 17, 2019 at 0:17

# J, 6 4 bytes

2!>:


Edit: I forgot that the binomial coefficient formula existed, so that lowers the bytecount. Also this is on the REPL or as a function with the input taken as the right argument. The other solutions need to be on the REPL, which I forgot to mention.

First post in a while, figured I'd submit the language I've been trying to learn recently. Not sure if you can specify one-indexing for ranges in J like with APL.

### Explanation

2!>:
>:  Increment
2!    n Choose 2


### Previous solution (6 bytes)

Explanation below

+/i.>:
>:  Add 1
i.    Range [0,n+1)
+/      Sum


### 7 byte solutions

Explanations beneath each

-:(*>:)
(*>:)  Hook: n * (n+1)
-:       Halve

-:(+*:)
(+*:)  Hook: n^2 + n
-:       Halve


# Röda, 13 bytes

{seq 1,_|sum}


Try it online!

# Vim, 4̶6̶ 251716 15 keystrokes

Thanks @CowsQuack for -9 bytes!

YP<C-a>Jr*0C<C-r>=<C-r>"/2⏎


Try it online!

### Ungolfed/Explained

YP                           " duplicate line containing N
<C-a>                      " increment the first line
J                     " join the two lines
r*                   " substitute space between N and N+1 with *
0C                 " delete line (store in " register) and insert
<C-r>=        ⏎  "   the expression
<C-r>"     "   from the " register
/2   "   divided by 2


# ArnoldC, 301 bytes

Well if Leo can find a way to do it in one byte, this is my way of throwing in the towel.

With the language based on the guy who never surrenders.

(And studying for the precalc final, you know, n(n+1)/2 is a formula I won't forget now, right?)

As of now, there's not really a way to take input in from the console from Try It Online, but this guy supposedly added something here.

Assuming that works, this code should do:

IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP 0
GET YOUR ASS TO MARS n
DO IT NOW
WHO IS YOUR DADDY AND WHAT DOES HE DO
HEY CHRISTMAS TREE a
YOU SET US UP n
GET TO THE CHOPPER a
HERE IS MY INVITATION a
GET UP 1
YOU'RE FIRED n
HE HAD TO SPLIT 2
ENOUGH TALK
TALK TO THE HAND a
YOU HAVE BEEN TERMINATED


If not, this should work, manually assigning variable n (although it's a bit against the challenge)

IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP 3
HEY CHRISTMAS TREE a
YOU SET US UP n
GET TO THE CHOPPER a
HERE IS MY INVITATION a
GET UP 1
YOU'RE FIRED n
HE HAD TO SPLIT 2
ENOUGH TALK
TALK TO THE HAND a
YOU HAVE BEEN TERMINATED


Try it online!

# Pyt, 1 byte

△


Try it online!

Explanation:

               implicit input
△             compute the nth triangle number

• Can you give a link to the codepage? Dec 24, 2017 at 20:11
• It's at the beginning of the interpreter2 file - the language is still a work in progress Dec 24, 2017 at 20:34
• I just added a link to the codepage Jan 12, 2018 at 1:11
• 1 byte Jan 28, 2018 at 21:04
• @cairdcoinheringaahing I never got around to editing all of my old answers once I made Pyt take input implicitly. I've edited some of them, but not all Jan 28, 2018 at 21:07

# brainfuck, 14 bytes

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


Try it online!

Takes input as character code, outputs as unary null bytes

# shortC,  44  29 bytes

Bn){K"%d",&n);R"%d",n*(n+1)/2


Try it online!

Just a shortCed version of this. Any help would be appreciated.

# Spice (56 bytes)

;a;b;c;d@
REA a;
ADD a 1 b;
DIV b 2 c;
MUL a c d;
OUT d;


# Explanation

The code is an implementation of the n*(n+1)/2 solution seen in other responses. It should be fairly readable but here's the code annotated:

;a;b;c;d@    - Declare 4 vars a, b, c and d (@ marks end of declarations)
REA a;       - Read in the value from the console and store in a
ADD a 1 b;   - Add 1 to a and store in b
DIV b 2 c;   - Divide b by 2 and store in c
MUL a c d;   - Mulitply a and c and store in d
OUT d;       - Output d to console


# C# (Visual C# Interactive Compiler), 2922 10 bytes

n=>n*++n/2


Try it online!

# C (gcc), 19 bytes

#define f(n)n*-~n/2


Try it online!

# C (gcc), 15 bytes

f(n){n*=-~n/2;}


-5 bytes thanks to ceilingcat!

Try it online!

• @ceilingcat Huh. How does that work? Jan 10, 2020 at 12:26
• @JL2210 It's abusing the way GCC compiles the code without optimizations. Jan 11, 2020 at 14:37
• 1+2+3+4+5+6=18?
– l4m2
Apr 21, 2021 at 10:53

# Hexagony, 16 bytes

?"&{2'<)}=*/@!:=

• You can get 15 pretty trivially by using chr(2). Try it online!
– Jo King
Jun 10, 2021 at 5:23
• @JoKing wow, I didn't even know that was a command, good find Jun 10, 2021 at 5:31
• It's a sort of accidental extension to the "All Letters set the edge to their ordinal value" rule, in that any non-instruction non-whitespace character sets its ordinal value, even unicode characters!
– Jo King
Jun 10, 2021 at 5:38
• wait really? I feel a bit dumb now, and that opens up more possibilities Jun 10, 2021 at 5:42

# Fourier, 9 bytes

I~_^*_/2o


Try it online!

# flax, 2 bytes

Σ⍸


## Explanation

Σ⍸
Σ     ⍝ sum of
⍸    ⍝ numbers from range 1...n


# Knight, 11 bytes

O/*+1=xPx 2


Try it online!

Ungolfed:

OUTPUT / (* (+1 = x PROMPT) x) 2


How the magic works:

This is using the fact that $$\\sum_{n=1}^{x} n == \frac{x(x + 1)}{2}\$$

1. =xP First, we read a line from standard input and assign to x. Normally, we would do +0P to immediately coerce it to a Number, but I have better plans.
2. +1=xP We add the result of the assignment to $$\1\$$. This coerces to Number for us, giving a result of Number.
3. *+1=xPx We then multiply that by x. Since +1=xP is a Number, x will also be converted to a Number. Now, we have $$\x(x + 1)\$$.
4. Last, divide by 2 and output.

# CJam, 6 bytes

ri),:+


Try it online!

### Explanation

ri    e# Read integer n
)     e# Add 1
,     e# Range from 0 to input argument minus 1
:+    e# Fold addition over array. Implicitly displa


# BLua, 32 bytes

r=0;for i=1,n r=r+i end;return r


Try it out (Vanilla Lua version, 53 bytes)

I'm not very good at this

# Swift, 13 bytes

Anonymous function:

{$0*($0+1)/2}


You can call it like this:

print({$0*($0+1)/2}(5))


Try it online!

# Mathematica, 9 bytes

#(#+1)/2&


or, at 11 bytes,

Tr@Range@#&


# AutoHotkey, 22 bytes

A(n){return n*(n+1)/2}


Defines a function that takes parameter n, and returns n*(n+1)/2, which is the nth triangle number, as shown in Leo's Husk answer.

• Are you sure about the - operator? Jul 18, 2017 at 22:36
• @OlivierGrégoire Sure that it's the subtraction operator? I'm as sure as the AHK docs are Jul 18, 2017 at 22:38
• Okay, it's just seems weird given that 1+...+n is usually equals to n*(n+1)/2 in maths, not n*(n-1)/2, but I don't know AutoHotkey and how it does maths, so I had to ask. Jul 18, 2017 at 22:44
• @OlivierGrégoire Oh right yeah no I'm a turd that's supposed to be a + Jul 18, 2017 at 22:53

# Tcl, 27 bytes

proc T n {expr $n*($n+1)/2}


Try it online!

# Casio Basic, 9 bytes

(n+1)n/2


8 bytes for the code, +1 to add n as parameter.

# Factor, 12 bytes

[ iota sum ]


Input is given as an argument to this anonymous function (quotation).

# Terrapin Logo, 16 bytes

OP (1+:N)*(:N/2)


# Commentator, 22 bytes

//
;-} {-
{-  -}<!-}!


Try it online!

# GolfScript, 7 6 bytes

~.)2/*


Try it online!

# Pip, 7 bytes

a*++a/2


Try it online!

# ><>, 20 15 bytes

:1-:?!v
n?=1l+<


@notatree saved me a couple bytes!

Try it online!

• Nice! You can save a byte by turning the second line into v?=1l+<, or if you don't mind exiting with an error, replace the second line with n?=1l+< and remove the last two lines. Jul 19, 2017 at 7:42
• @Notatree Thanks! Jul 19, 2017 at 7:55