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

## Clojure - 19 bytes

#(apply +(range %))

# Labyrinth, 8 bytes

?:)*_2/!


Try it online!

A linear program which halts by error at the bounced-off / (triggering division by zero).

?:)*  Push input, dup, increment, multiply (giving n*(n+1))
_2/   Divide by 2
!     Pop and print, bounce off the dead end
/     The top is (implicit) 0 so it triggers division by zero error


## <>^v, 8 bytes

,≈)*2?/;


#### Explanation

,≈)*2?/;

≈        Duplicate top of stack
)       Increment top of stack
*      Multiply top element of stack by second element of stack
2     Push 2
?    Swap top two elements of stack
/   Divide top element of stack by second element of stack
;  Print top of stack


run online

# Tcl, 36 bytes

time {incr s [incr n]} $argv;puts$s


Try it online!

# Tcl, 29 bytes

puts [expr $argv*($argv+1)/2]


Try it online!

• If you've got two Tcl answers, you should probably put them in one answer. Jul 19 '17 at 0:24
• @numbermaniac I have three. Jul 19 '17 at 0:29
• Ah. It's probably better to put them all in one answer, then. Jul 19 '17 at 1:08

# QBIC, 10 bytes

?(:+1)/2*a


This prints (input+1) divided by 2 times input. Looping through all numbers from 1 to n is one byte longer:

[:|p=p+a]?p


# Pyke, 2 bytes

Ss


Try it online!

Showing off Pyke's roots in being inspired by Pyth, the function map is exactly the same, only ran as a stack rather than a tree.

S  -  range(1, input+1)
s - sum(^)


# Scala, 12 bytes

### Gauss sum (12 bytes):

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


### Naive version (14 bytes):

n=>1.to(n).sum


# Clojure, 28 bytes

#(apply + (range 1 (inc %)))


# Java 8 (39 37 bytes)

n->{System.out.println((n*(n+1))/2);}


saved 2 bytes thanks to @TheLethalCoder. I now realise that I could also omit print statements etc, but there already is a Java answer that I missed, which would end up being pretty much the same thing. Thus I will leave it as this :-)

(Is this the right way of scoring Java? I have no clue if this is valid, I saw it in another answer but this actually omits quite a bit of the code necessary to actually run it..)

try it online

• (n) can be just n. You can return from the lambda, I believe, instead of printing. And yes it's fine to compile to a lambda. Jul 19 '17 at 12:34
• Side note: Use four spaces to format the code not back ticks. Jul 19 '17 at 12:34
• @TheLethalCoder thanks! I just found another Java answer to this thread which indeed does it a great deal shorter and does not print ^^ Jul 19 '17 at 12:34

# Clojure, 16 bytes

#(/(*(inc %)%)2)


# Groovy, 11 bytes

{it*++it/2}


Try it online!

The input is not modified by rules of Groovy clsures.

# PHP, 353432 25 bytes

<?=$argv[1]*++$argv[1]/2;


Run from the command line, with the input as a parameter.

• Save 6 bytes with $argn and -F Jul 26 '17 at 11:34 # Fortran 95, 58 bytes function l(n) i=1 l=1 do while(i<n) i=i+1 l=l+i end do end  Try it online! ## Dyvil, 12 bytes n=>n*(n+1)/2  The operator rules force me to use either parentheses or spaces. Uses the Gauss method, and is also a Scala polyglot. Usage: let f: int -> int = n=>n*(n+1)/2 print f(5) // 15 print f(10) // 45  # Swift 3, 60 Bytes var b=Int.init(readLine()!)! (1..<b).forEach{b+=$0}
print(b)


Try it online!

## Matlab/Octave, 12 bytes

@(n)sum(1:n)


# Perl 5, 11 bytes

10 bytes of code + 1 for -p

$_*=$_++/2


Try it online!

# Math++, 13 bytes

?>n
(n*n+n)/2


# Pushy, 3 bytes

RS#


Try it online!

## How it works

    - Implicit input on the stack e.g. 5;    STACK = [5]
R   - Generate a range from 1 to n;          STACK = [1 2 3 4 5]
S  - Sum the stack;                         STACK = [15]
# - Output top of the stack as an integer; DISPLAY 15

• Wow, someone other than me used Pushy! Quick correction: R generates from 1 to n, not 0 to n. Oct 24 '17 at 18:57
• @FlipTack ah, thanks! The docs are a little confusing with X and R Oct 24 '17 at 18:58
• Also, summing does not remove the items it is summing, so the stack finishes as [1,2,3,4,5,15] Nov 21 '17 at 7:32

## Python 3, 35 bytes

print(sum(range(1,int(input())+1)))

• You can save 2 bytes by removing the 1, in the range argument. Try it online! Nov 2 '17 at 7:57

# Implicit, 2 bytes

¡Þ


Try it online!

    implicit integer input
¡   push 1..n
implicit integer output


Version without builtins:

# Implicit, 13 12 bytes

(:-1)[(]+[)]


The popping of 0 is unnecessary due to updates. Old version:

(:-1);[(]+[)]


Try it online! Explanation:

(:-1);[(]+[)]
(...)           do..while top of stack truthy
:               duplicate (implicit input if stack empty)
-1             subtract 1 from top of stack
;          pop the last value (will be 0)
[         pop stack into memory
(...)    do..while top of stack truthy
]       pull memory
+      add top two stack values together
[     pop into memory
implicit output


Ok, so that's a bit confusing. (I don't really know how it works myself). Let's go step-by-step for the input 5.

(:-1);[(]+[)]
(...)
:-1            stack: 5, 4
:-1            stack: 5, 4, 3
:-1            stack: 5, 4, 3, 2
:-1            stack: 5, 4, 3, 2, 1
:-1            stack: 5, 4, 3, 2, 1, 0
;          stack: 5, 4, 3, 2, 1
[         stack: 5, 4, 3, 2
(...)
]       stack: 5, 4, 3, 2, 1
+      stack: 5, 4, 3, 3
[     stack: 5, 4, 3
]       stack: 5, 4, 3, 3
+      stack: 5, 4, 6
[     stack: 5, 4
]       stack: 5, 4, 6
+      stack: 5, 10
[     stack: 5
]       stack: 5, 10
+      stack: 15
[     stack: empty (exits loop)
]  stack: 15
implicit output


# C (gcc) 16 bytes

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


Try it online

• Would it be possible to use n*=...? Dec 27 '17 at 12:48
• @Zacharý that gives the wrong output for some input Dec 27 '17 at 15:45
• Whoops, forgot about order of operation Dec 27 '17 at 17:07

# Aceto, 9 bytes

ridIU2:*p

ri reads input and converts to int
d duplicates the value
I increments the top value by one
U reverses the stack
2: divides by 2
* multiplies the top two values
p prints it


Try it online!

# COBOL (GNU), 164 bytes

Requires the -F flag (+2 bytes)
Uses the formula N*(N+1)/2

IDENTIFICATION DIVISION.PROGRAM-ID.S.DATA DIVISION.WORKING-STORAGE SECTION.
01 N PIC 9(9) VALUE ZEROES.PROCEDURE DIVISION.ACCEPT N.COMPUTE N=N*(N+ 1)/2.DISPLAY N.


Try it online!

Ungolfed:

       IDENTIFICATION DIVISION.
PROGRAM-ID. S.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 N	PIC 9(5) VALUE ZEROES.
01 R	PIC 9(9) VALUE ZEROES.

PROCEDURE DIVISION.
ACCEPT N
COMPUTE R=N*(N+ 1)/2
DISPLAY R.


# COBOL (GNU), 362 bytes

Explicitly computing the sum

       IDENTIFICATION DIVISION.
PROGRAM-ID. S.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 N	PIC 9(5) VALUE ZEROES.
01 T	PIC 9(5) VALUE ZEROES.
01 R	PIC 9(9) VALUE ZEROES.

PROCEDURE DIVISION.
ACCEPT N.
PERFORM VARYING T FROM 1 BY 1 UNTIL T > N
END-PERFORM.
DISPLAY R.


Try it online!

Because COBOL uses fixed-size variables, both of these work for values of n up to 44720. Anything larger doesn't fit in the specified 9 decimal digits of the result, although that is easily resolved by changing PIC 9(9) to PIC 9(10).

# Windows batch, 57 21 bytes

Inspired by J42161217

@cmd/cset/a%1*(%1+1)/2


# Functoid, 29 bytes

Most likely the characters $.@ don't count to the total, but this isn't going to win anyway.. Y(BBxZK0(BBB(C(BBS))CB[+))$.@


Try it online!

### Explanation

Y(                       )     # find fixpoint of the function
x                            # single argument recursive helper with
Z                           #   - base case (== 0)
(K0)                       #   - in base case: constant 0
(BBB(C(BBS))CB[+)      #   - recursive function ( add (+) argument to recursive call of argument decremented by 1 ([) )
$# apply argument . # simplify & print as Church numeral @ # exit  The massive combinator BBB(C(BBS))CB is possibly still golfable, I'm still learning how to golf lambda calculus combinators and I find it rather tricky.. # Broccoli, 35, 33 bytes (fn t ($n) (/ (* $n (+ 1$n)) 2))


Defines a function 't' that can be called like so:

(t 10)

• Surely n*(n+1)/2 should be shorter, even in this ridiculous language
– user45941
Jan 12 '18 at 5:25
• @Mego Surprisingly, not by very much. And it outputs it as a float, not an int. I hope that's OK. Jan 12 '18 at 5:37
• I don't see why outputting as a float wouldn't be valid. There's a JS answer already.
– user45941
Jan 12 '18 at 5:38
• (fn t($n)(/(*$n(+ 1 $n))2)) works too Mar 16 '18 at 0:38 # Pyt, 2 bytes řƩ  Try it online! implicit input ř returns [1, 2, 3, ... , top value] Ʃ sums top value implicit output golfed by mudkip # Clean, 26 bytes import StdEnv$n=sum[1..n]


Try it online!

And also

# Clean, 26 bytes

import StdEnv
\$n=n*(n+1)/2


Try it online!