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

• 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

# 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 # 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. # 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. – Zacharý 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. – Zacharý 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) – Zacharý 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 – DJMcMayhem 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 # 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 – HyperNeutrino 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 }. – Zacharý Jul 19 '17 at 17:23
• Um ... actually the first two solutions don't work... C is case sensitive! – Zacharý Jul 23 '17 at 16:18
• also change (n+1) to -~n: #define F(n)-~n*n/2 – dingledooper Oct 17 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.

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

### Previous solution (6 bytes)

Explanation below

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

### 7 byte solutions

Explanations beneath each

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

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