# 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 – FryAmTheEggman Jul 18 '17 at 20:36
• @FryAmTheEggman Sorry - had a bit of a brain fart there. I see what you mean. – GarethPW Jul 18 '17 at 20:45
• @Aaron you got ninja'd by Husk, which was just posted with a 1 byte solution – Skidsdev Jul 18 '17 at 21:35
• I suggest a stack snippet. – programmer5000 Jul 19 '17 at 11:42
• – Jerry Jeremiah Jul 27 '17 at 12:20

# 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. – Peter Cordes Jul 22 '17 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 – Peter Cordes Jul 22 '17 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. – Cody Gray Jul 22 '17 at 11:08

# 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! – FryAmTheEggman Jul 18 '17 at 21:10

# 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! # 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  # 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; }  # 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 ( – Roman Gräf Jul 19 '17 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 – Skidsdev Jul 19 '17 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 , – Skidsdev Jul 19 '17 at 8:35 • I don't thinm editing the name of a feature after the realese of the challenge is valid tho... – Roman Gräf Jul 19 '17 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 – Skidsdev Jul 19 '17 at 9:07 # 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. – programmer5000 Jul 19 '17 at 11:24 # 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! – Stephen Jul 19 '17 at 13:04 # 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 – rexkogitans Jul 19 '17 at 16:32 • @rexkogitans Edited! Thanks – Ivan Botero Jul 21 '17 at 16:34 # 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. – Adalynn Jul 30 '17 at 17:52 • TI-BASIC is the language that is used on most Texas instruments graphics calculators; what should I link to? – user1812 Jul 31 '17 at 18:40 • Or remove the brackets. – Adalynn Jul 31 '17 at 18:48 • Alternatively sum(randIntNoRep(1,N – Oki Sep 9 '17 at 11:50 • Wow! Didnt think of that :D It is unfortunate that randIntNoRep() is 2 bytes not 1. – user1812 Sep 9 '17 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  # Python 2, 16 bytes lambda n:-~n*n/2  Try it online! • Welcome to PPCG! – Martin Ender Jul 19 '17 at 16:56 • Is there any problem in my answer? – Rohit-Pandey Jul 19 '17 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) – Adalynn Jul 19 '17 at 17:22 • Where is n defined? – Eric Duminil Jul 20 '17 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! – Business Cat Jul 20 '17 at 18:27 # 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? – lirtosiast Aug 25 '17 at 0:33 • @lirtosiast True, that didn't occur to me. – Timtech Aug 25 '17 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 – James Jul 18 '17 at 21:14 • Yep, just submitted it for speed, thanks for the notice! – Snaddyvitch Dispenser Jul 18 '17 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! – FryAmTheEggman Jul 18 '17 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) – Value Ink Jul 18 '17 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. – Value Ink Jul 18 '17 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 – ASCII-only Jan 30 '19 at 9:38 # 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 – AdmBorkBork Jul 18 '17 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 – hyper-neutrino Jul 19 '17 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 {[+] ^$_} – Massa Sep 8 '17 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. – Brad Gilbert b2gills Sep 8 '17 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 '17 at 8:47
• @Okx I could've sworn i tried that, thanks. – LiefdeWen Jul 19 '17 at 8:56

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

# Common Lisp, 26 bytes

(lambda(n)(/(+(* n n)n)2))

• Hello, and welcome to the site! – programmer5000 Jul 19 '17 at 11:31

# 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. – Maxim Mikhaylov Jul 19 '17 at 2:22
• And it would be even shorter to just use sum(1:scan()) – Giuseppe Jul 19 '17 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). – djhurio Jul 19 '17 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. – Forgottenscience Jul 19 '17 at 10:42
• It should be sum(1:scan()), not sum(1:scan(n)). – djhurio Jul 19 '17 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}; – Uriel Jul 18 '17 at 23:13
• And for the "code and math" section, you don't need the semicolon after the }. – Adalynn Jul 19 '17 at 17:23
• Um ... actually the first two solutions don't work... C is case sensitive! – Adalynn Jul 23 '17 at 16:18
• also change (n+1) to -~n: #define F(n)-~n*n/2` – dingledooper Oct 17 '19 at 0:17