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

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

# Triangular, 10 bytes

$\:_%i/2*<  Ungolfed: $
\ :
_ % i
/ 2 * <


Try it online!

The code, without directionals, is read as $:i*2_%. • $ reads an integer x, stack contains {x}.
• : duplicates it, stack contains {x,x}.
• i increments the top of stack, stack contains {x,x+1}.
• * multiplies the top two stack values, stack contains {x*(x+1)}.
• 2 pushes 2 to the stack, stack contains {x*(x+1),2}.
• _ divides the top two stack values, stack contains {x*(x+1)/2}.
• % prints the top of stack, the equation x*(x+1)/2.

Idea thanks to caird, who asked me to post.

# Cubix, 12 10 bytes

*,)2I://O@


### Initial version

....I:)*2,O@


Try it online!

# Explanation

Expanded onto a cube, the code looks like this:

    * ,
) 2
I : / / O @ . .
. . . . . . . .
. .
. .


The instruction pointer (IP) starts at the I, moving east. It continues moving east until it comes across the / mirror, which reflects it north. When the IP reaches the top of the code, it wraps around to the last . on the third line, moving south. Then it wraps to the penultimate . on the last line, moving north. Then it reaches the / mirror again, which reflects it east, only for the next / to reflect it north again. This time, the IP wraps to the penultimate . on the third line, and then the last . on the last line.

The instructions are executed in the following order.

I:)*2,O@ # Explanation
I        # Take input as an integer and push it to the stack
:       # Duplicate the input
)      # Increment one of the inputs
*     # Multiply the input by input+1
2    # Push 2 to the stack
,   # Integer devide the multiplication result by 2
O  # Output the result
@ # End program


# x86-64 Machine Code, 7 bytes

31 C0
01 C8
E2 FC
C3


The above bytes define a function that accepts a single parameter, n, and returns a value containing the sum of all integers from 1 to n.

It is written to the Microsoft x64 calling convention, which passes the parameter in the ECX register. The return value is left in EAX, like all x86/x86-64 calling conventions.

Ungolfed assembly mnemonics:

       xor  eax, eax    ; zero out EAX
loop Next        ; decrement ECX by 1, and loop as long as ECX != 0
ret              ; return, with result in EAX


Try it online!
(The C function call there is annotated with an attribute that causes GCC to call it using the Microsoft calling convention that my assembly code uses. If TIO had provided MSVC, this wouldn't be necessary.)

By the unusual standards of code golf, you see that this iterative looping approach is preferable to approaches that use the more sane mathematical formula (n(n+1) / 2), even though it is obviously vastly less efficient in terms of run-time speed.

Using number theory, ceilingcat's implementation can still be beat by one byte. Each of these instructions are essential, but there is a slightly shorter encoding for IMUL that uses EAX implicitly as a destination operand (actually, it uses EDX:EAX, but we can just ignore the upper 32 bits of the result). This is only 2 bytes to encode, down from 3.

LEA takes three bytes as well, but there's really no way around that because we need to increment while preserving the original value. If we did a MOV to make a copy, then INC, we'd be at 4 bytes. (In x86-32, where INC is only 1 byte, we'd be at the same 3 bytes as LEA.)

The final right-shift is necessary to divide the result in half, and is certainly more compact (and more efficient) than a multiplication. However, the code should really be using shr instead of sar, since it's assuming that the input value, n, is an unsigned integer. (That assumption is valid according to the rules, of course, but if you know that the input is unsigned, then you shouldn't be doing a signed arithmetic shift, as the upper bit being set in a large unsigned value will cause the result to be incorrect.)

8D 41 01                lea    eax, [rcx+1]
F7 E9                   imul   ecx
D1 E8                   shr    eax, 1
C3                      ret


Now only 8 bytes (thanks to Peter Cordes). Still, 8 > 7.

• Actually, one-operand imul ecx or mul ecx would work and save a byte in the closed-form implementation. I didn't spot that right away; I was about to comment that it was optimal for both performance and code-size before realizing that an implicit eax operand was fine. Jul 22, 2017 at 8:42
• I wondered if add+loop would be shorter than imul while looking at the other answer. Handy that there's a standard calling convention that passes the first arg in ecx Jul 22, 2017 at 8:45
• Wow, I can't believe I missed the one-operand form! I should really know by now not to say things like "cannot be beat". When will I learn?! Thanks, @Peter. Jul 22, 2017 at 11:08

# 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. # ArnoldC, 310 bytes Removes unnecessary variable assignments from Courtois' solution and replaces them with GET TO THE CHOPPER and some arithmetic operations. IT'S SHOWTIME HEY CHRISTMAS TREE n YOU SET US UP 0 GET YOUR ASS TO MARS n DO IT NOW I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY GET TO THE CHOPPER n HERE IS MY INVITATION n GET UP 1 YOU'RE FIRED n HE HAD TO SPLIT 2 ENOUGH TALK TALK TO THE HAND n YOU HAVE BEEN TERMINATED  Who doesn't like some good Arnold Schwarzenegger one liners :) Try it online! # Python 2, 16 bytes lambda n:-~n*n/2  Try it online! • Welcome to PPCG! Jul 19, 2017 at 16:56 • Is there any problem in my answer? Jul 19, 2017 at 17:03 • You can save a byte by changing it to print(n+1)*n/2 (Someone might already have print(n+1)*n/2 as answer though) Jul 19, 2017 at 17:22 • Where is n defined? Jul 20, 2017 at 8:59 • Our consensus is that submissions must be full programs or functions, of which yours is neither (yours is a snippet, as in it needs other code to run properly). You could fix it by counting the assignment of input() to n in your submission or changing it to a function/lambda that returns the result. By the way, welcome to PPCG! Jul 20, 2017 at 18:27 # Hexagony, 14 bytes ?'+\.*:){=/\!2  Expanded out, this is:  ? ' + \ . * : ) { = / \ ! 2 . . . . .  It took quite a bit of effort to get from a trivial 15 byte modification of Underslash's answer (using a char literal for 2), to get to 14 bytes. We save that one byte by managing to reuse all of '{= at the cost of an extra control flow instruction, as well as by terminating through an error of division by zero. There's still one no-op in the middle of this, so perhaps 13 is possible (but unlikely)? Expanding it out by following the control flow, we find this: ?'+){=*'2{+*=2?*:!2)+*=2?*:  Removing all the extra stuff that are basically no-ops or are there to force a specific path of execution, we get: ?'+){=*'2{=:!=: ? Get the input '+ Duplicate it to an adjacent edge ) Increment it {=* Multiply the original by the incremented one '2 Place 2 in an adjacent cell {=: Divide the result by 2 ! And print =: Divide by zero  # Ohm, 2 bytes @Σ  Try it online! ## Explanation @Σ implicit input @ inclusive range [1..input] Σ sum implicit output  # WendyScript, 17 bytes <<f=>(x)x*(x+1)/2 f(100) // => 5050  Try it online! # cQuents, 2 bytes ;$


This is the type of question that cQuents was designed for, and the type of question I implemented the ; mode for. Take that, Oasis!

Try it online!

### Explanation

;    Mode: Sum (output sum of sequence up to input)
$Each item in the sequence is its (1-based) index  # Brachylog, 2 bytes ⟦+  Try it online! ### Explanation ⟦ Range: [0, …, Input] + Sum: 0 + … + Input  # Lean Mean Bean Machine, 38 32 bytes -5 bytes thanks to Roman Gräf -1 byte from changing LMBM's division peg from £ to ,  O O i 2 o )/ , / / * u  ## Explanation Each O spawns a marble at program start. The first marble reads input and has it's value set to it, the 2nd has it's value set to 1, and the 3rd has it's value set to 2. The n-marble is then duplicated, one copy falls all the way to a multiplication operator, where it will be held for a 2nd marble, the other falls into a subtraction operator, which the 1-marble then falls into after it. This new n-1-marble then falls into a division operator (,), and the 2-marble falls in right after it. This (n-1)/2-marble then falls into the multiplication operator, and the final n*(n-1)/2 marble falls into a u peg, where its value is printed, and the marble is destroyed. • Isn't there decrement peg? I'm pretty sure it is either ) or ( Jul 19, 2017 at 8:00 • @RomanGräf I literally used that peg in another challenge like 5 minutes before writing this answer, I'm an idiot :P Jul 19, 2017 at 8:32 • I also forgot that despite being typeable on my UK keyboard layout, £ is not a 1-byte character. Changed division character to , Jul 19, 2017 at 8:35 • I don't thinm editing the name of a feature after the realese of the challenge is valid tho... Jul 19, 2017 at 8:36 • @RomanGräf Community Consensus allows newer versions of languages, and given this is not at all a change specific for this challenge (having the division operator be 2 bytes is a pretty big issue), I don't think it's a problem Jul 19, 2017 at 9:07 # Bash, 26, 19 bytes echo$[($1+1)*$1/2]


Try it online!

19 bytes for the code, thanks to rexkogitans.

• echo $[($1+1)*$1/2] 19 bytes Jul 19, 2017 at 16:32 • @rexkogitans Edited! Thanks Jul 21, 2017 at 16:34 # 8th, 21 12 bytes Saved 9 bytes thanks to FryAmTheEggman dup 1+ * 2 /  Usage and output ok> : sum dup n:1+ * 2 / ; ok> 5 sum . 15  • Actually, I think you saved 9 bytes thanks to Gauss ;) But thanks for the credit! Jul 18, 2017 at 21:10 # TI-BASIC, 6 bytes Beating Casio-basic by 3 bytes :) 6 byte version thanks to PT_ from cemetech (https://www.cemetech.net/forum/profile.php?mode=viewprofile&u=10064) mean({N²,N  Two other, 7 byte, versions: .5N(N+1 .5(N²+N  • You might want to make TI-BASIC link to something. Jul 30, 2017 at 17:52 • TI-BASIC is the language that is used on most Texas instruments graphics calculators; what should I link to? Jul 31, 2017 at 18:40 • Or remove the brackets. Jul 31, 2017 at 18:48 • Alternatively sum(randIntNoRep(1,N – Oki Sep 9, 2017 at 11:50 • Wow! Didnt think of that :D It is unfortunate that randIntNoRep() is 2 bytes not 1. Sep 9, 2017 at 22:37 # brainfuck, 24 bytes Input number in base255(ASCII), use bigger cells for larger numbers, outputs also in base255. ,[[>+>+<<-]>[-<+>]<-]>>.  Try it online! For bigger cells.  ,[ Get input in base 255 mod 2^bit [ >+ Copy it left(to preserve index) >+ and left left to accumulate the sum <<- ] decrement index to break loop > Move to the first copy, index'in [-<+>]Move it back, restoring the index <- ] Decrement index, let function run again until 0 >>. Print sum  # Symbolic Python, 353318 16 bytes _=-~_*_/-~(_==_)  Try it online! Uses the direct formula for triangle numbers, (n+1)(n/2): _= # Set output to -~_ # (n+1) *_ # *n /-~(_==_) # /2  # TI-Basic, 6 bytes sum(randIntNoRep(1,Ans  Alternate solutions: mean({AnsAns,Ans 6 bytes credits to @user1812 .5Ans(Ans+1 7 bytes .5(AnsAns+Ans 7 bytes Σ(I,I,1,Ans 9 bytes sum(seq(I,I,1,Ans 9 bytes  • Why not sum(randIntNoRep(1,Ans? Aug 25, 2017 at 0:33 • @lirtosiast True, that didn't occur to me. Aug 25, 2017 at 2:21 ## Ruby, 29171814 12 bytes ->n{n*-~n/2}  Execution: ->n{n*-~n/2}.call(5)  Gets The Value of the sum of 1 through 5 Try It Out! People Who Have Saved Me A Few Bytes: Saved 12 Bytes - DJMcMayhem Saved 6 Bytes - FryAmTheEggman Unsaved 3 Bytes (But Added Variable Handling) - Value Ink Fixed A Misunderstanding, Saving me 8 Bytes - Value Ink Saved 2 Bytes - G B Many Thanks! • Wouldn't this be shorter with a different name? Like s instead of sum? Also, I think you could remove some spaces Jul 18, 2017 at 21:14 • Yep, just submitted it for speed, thanks for the notice! Jul 18, 2017 at 21:15 • Hi and welcome to PPCG! Our standard methods of input does not include the value being stored in a variable. I think you should be able to get a similar score using an unnamed lambda function. I think you can also do better by using Gauss' formula. I hope you enjoy your time here! Jul 18, 2017 at 21:28 • You still need to use a function. A snippet that assumes you set a variable beforehand and sets a new variable, like what you have, is not allowed. In Ruby, this is achieved with ->n{your code}, and it will automatically return whatever you input. Run with ->n{your code}.call(5) Jul 18, 2017 at 21:56 • You don't need the .call(5). That's just an example of how you'd call the function. For example, p ->n{your code}.call(5) prints the result of the function for n=5. Jul 18, 2017 at 23:31 # Alchemist, 40 bytes 0x+_->a+Out_I 0_+0x+a->x x+a->_+x x+0a->  Outputs in unary, try it online or try it with automatic conversion to decimal! ## Explanation We'll 3 types of atoms the $$\\texttt{_}\$$-, $$\\texttt{x}\$$- and $$\\texttt{a}\$$-atoms: • $$\\texttt{_}\$$ initially is the input • $$\\texttt{x}\$$ is to make sure the computation is deterministic • $$\\texttt{a}\$$ # When there is no x-atom but still _ left, transform it to a and output I 0x + _ -> a + Out_I # If there are no _- and x-atoms but still at least one a, we remove one a and add an x 0_ + 0x + a -> x # If there is an x-atom, exchange all a-atoms for _-atoms x + a -> _ + x # Once we're done with that, remove the x-atom (this makes the first rule applicable again, creating a loop) x + 0a -> So essentially we transform each $$\\texttt{_}\$$ to $$\\texttt{a}\$$ while outputting an $$\\texttt{I}\$$, remove one $$\\texttt{a}\$$ and exchange them back to $$\\texttt{_}\$$, until there are no $$\\texttt{a}\$$-atoms and no rule is applicable anymore - terminating the progress of the universe. • :/ 64 Jan 30, 2019 at 9:38 # tinylisp, 30 bytes (d F(q((n)(i n(a n(F(s n 1)))0  Try it online! # Vyxal s, 1 byte ɾ  Inclusive range of 1 to input, and s flag sums the stack. Try it! • Wouldn't this count as 2 since the flags are counted? May 12, 2021 at 1:36 • @Underslash flags aren't counted May 12, 2021 at 1:54 • Unless I'm remembering wrong, aren't flags counted as a byte each because you can abstract away code with them? May 12, 2021 at 6:48 • @Underslash Nope. Instead, "Vxyal s" is considered an entirely separate language from "Vyxal". I'm not sure what you mean by "abstract away code", but overuse of command like flags to store code makes the answer violate the standard loophole "using a made-up language designed specifically for the challenge" May 17, 2021 at 3:07 # PowerShell, 22 18 bytes param($n)$n*++$n/2


Try it online!

Saved 4 bytes thanks to FryAmTheEggman. Uses Gauss' formula. Ho-hum.

• @FryAmTheEggman You'd think so, and you'd be right. :p Jul 18, 2017 at 20:53

# Positron, 27 bytes

Positron is a new practical language by @HyperNeutrino.

function{return$1*($1+1)/2}


Try it online!

• Yay I'm happy :D Jul 19, 2017 at 1:25

# Perl 6, 11 bytes

{[+] 1..$_}  Try it { } creates a lambda block with implicit parameter $_
1 .. $_ creates a Range object [+] reduces it using the &infix:«+» operator. (Rakudo actually calls the sum method on the Range object if you haven't lexically modified the &infix:«+» operator, and the sum method knows how to calculate the result without iterating through all of the values) • You can save 2 more bytes with {[+] ^$_} Sep 8, 2017 at 14:12
• @Massa That would exclude the $_ as it is short for 0 ..^$_, so it would need to be ^\$_+1 which is exactly the same length as what I have. Sep 8, 2017 at 15:10

# Element, 32 Bytes

_'1 z;0 t;[z~2:z;t~+t;z~1+z;]t~


Try it online!

Probably can go shorter, but late now...

# Neim, 3 2 bytes

𝐈𝐬


Try it online!

Explanation

𝐈   # Gets inclusive range from 0 to input
𝐬   # Sum the list


Saved a byte due to Okx

• Nein has implicit input, so you can remove the first byte :)
– Okx
Jul 19, 2017 at 8:47
• @Okx I could've sworn i tried that, thanks. Jul 19, 2017 at 8:56

# C, 56 47 bytes

main(n){scanf("%d",&n);printf("%d",n*(n+1)/2);}


This is my first attempt at any code golf of any kind. Submitted as I saw that there were no other answers for C.

Old code:

int main(){int n;scanf("%d",&n);printf("%d",n*(n+1)/2);}


Thanks to programmer5000 for the help. :)

• Welcome to the site! Nice first golf! You may be interested in some tips for golfing in C.
– user58826
Jul 19, 2017 at 11:24
• you can use -~n instead of (n+1) to make it 45 bytes main(n){scanf("%d",&n);printf("%d",n*-~n/2);} :) Feb 12 at 5:43

# MUMPS, 15 bytes

r n w !,n*n+n/2


Accepts user input (r n) and writes a new line along with the sum (w !,n*n+n/2). Order of operations doesn't matter in MUMPS: It goes from left to right except when there are parentheses.

• Welcome to PPCG! Jul 19, 2017 at 13:04

# Excel, 12 bytes

=(A1+1)/2*A1


Or, alternatively:

=(A1^2+A1)/2


Instead of counting all n elements, take the average of the n` elements, and multiply it by the number of elements.