85
\$\begingroup\$

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>

\$\endgroup\$
10
  • 5
    \$\begingroup\$ Closely related \$\endgroup\$ Commented Jul 18, 2017 at 20:36
  • \$\begingroup\$ @FryAmTheEggman Sorry - had a bit of a brain fart there. I see what you mean. \$\endgroup\$
    – Gareth
    Commented Jul 18, 2017 at 20:45
  • 2
    \$\begingroup\$ @Aaron you got ninja'd by Husk, which was just posted with a 1 byte solution \$\endgroup\$
    – Mayube
    Commented Jul 18, 2017 at 21:35
  • 7
    \$\begingroup\$ I suggest a stack snippet. \$\endgroup\$
    – user58826
    Commented Jul 19, 2017 at 11:42
  • 1
    \$\begingroup\$ Related: minecraftforum.net/forums/off-topic/… \$\endgroup\$ Commented Jul 27, 2017 at 12:20

222 Answers 222

1 2 3
4
5
8
2
\$\begingroup\$

shell, 17 14 bytes

First attempt was:

seq -s+ -t0 $1|bc

But not all implementations of seq know -t option. Second attempt is:

seq -s+0 $1|bc
\$\endgroup\$
4
  • \$\begingroup\$ there is no -t option to seq(1), but seq -s+ 0 $1|bc or seq -s+ $1|bc works \$\endgroup\$
    – c--
    Commented Jan 31, 2023 at 18:06
  • \$\begingroup\$ mine knows -t but it seems that GNU/Linux and OpenBSD implementations doesn't. I suppose your implementation still terminates with new-line, cause here seq -s+ 5 yields 1+2+3+4+5+ which turns to "Parse error: bad expression" for bc \$\endgroup\$
    – gildux
    Commented Jan 31, 2023 at 19:44
  • \$\begingroup\$ 13 bytes bash solution from 2017.. \$\endgroup\$
    – roblogic
    Commented Mar 23, 2023 at 17:00
  • \$\begingroup\$ I've missed that post @roblogic :( It has the same issue (my MacOS and my FreeBSD are resulting to the parse error) \$\endgroup\$
    – gildux
    Commented Mar 24, 2023 at 18:15
2
\$\begingroup\$

Erlang 19 bytes

s(N) -> N*(N+1)/2.
\$\endgroup\$
2
\$\begingroup\$

NASM 32 bits, 719 bytes

I am learning Assembly and used this golf challenge as a context for learning. Probably not the best, but it works.

Note: This version can only take a digit as an input (1 byte character)

section .data
a: equ 1
section .bss
b: resb a
section .text
global _start
_start:
mov eax, 3
mov ebx, 0
mov ecx, b
mov edx, a
int 80H
cmp eax, -1
jz _exit_1
mov edi, eax
atoi:
mov eax, 0
mov ebx, 0
c:
movzx esi, byte [ecx]
cmp ebx, edi
je d
cmp esi, 48
jl _exit_1
cmp esi, 57
jg _exit_1
sub esi, 48
imul eax, 10
add eax, esi
inc ecx
inc ebx
jmp c
d:
mov ecx, eax
mov eax, 0
.count:
add eax, ecx
dec ecx
cmp ecx, 0
jne .count
print_uint32:
xor ebx, ebx
mov ecx, 10
push ecx
mov esi, esp
add esp, 4
.e:
inc ebx
xor edx, edx
div ecx
add edx, '0'
dec esi
mov [esi], dl
test eax, eax
jnz .e
mov edx, ebx
mov eax, 4
mov ebx, 1
mov ecx, esi
int 80h
_exit_0:
mov eax, 1
mov ebx, 0
int 80H
_exit_1:
mov eax, 1
mov ebx, 1
int 80H

Try it online (This is 32 bit assembly, it will not run on TIO's 64 bit assembly online compiler.)

You can find a "non factorized" and commented code here

\$\endgroup\$
1
  • \$\begingroup\$ You can remove the spaces after the commas. \$\endgroup\$
    – ceilingcat
    Commented May 30, 2023 at 8:26
2
\$\begingroup\$

PIC16F88x Machine Code, 5 words (70 bits)

A function that expects its input at address 0x70, and returns via register W.

70 bits can't be represented cleanly in hex, so here's the raw binary:

00 0001 0000 0000
00 0111 0111 0000
00 1011 1111 0000
10 1000 0000 0110
00 0000 0000 1000

This assumes the function is located at address 0x005. It would be the same length no matter where I put it, but I have to hardcode the GOTO destination.

In mpasm syntax:

    ORG 5         ; Linker directive: place the function at address 0x005
sum:
    CLRW          ; Zero the W register
sum_sub0:
    ADDWF 0x70,0  ; Add the value to W
    DECFSZ 0x70,1 ; Decrement the value, skipping the next instruction if it
                  ; reached zero
    GOTO sum_sub0 ; Loop
    RETURN        ; Return

The PIC16F88x have no multiply instruction, so I have to loop. It might be possible to do better if there's a clever bitwise way to avoid multiplication.

\$\endgroup\$
2
\$\begingroup\$

(,) i, 280 273 49 33 30 Chars or \$30\log_{256}(3)\approx\$ 5.94 Bytes

(,,((),(())(),,,(),,((()))()))

Massive golf (224 chars) by taking input in unary.
Another golf (16 Chars) by realizing that input length doesn’t have to be stored in a variable.
No longer taking input in unary!
TIO

\$\endgroup\$
2
\$\begingroup\$

Go, 29 bytes

A function literal which uses the closed form, \$ \frac n2(n+1) \$.

func(n int)int{return-^n*n/2}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ ~ is not allowed outside of interfaces or type constraints. 31 bytes. \$\endgroup\$
    – bigyihsuan
    Commented May 16, 2023 at 13:21
2
\$\begingroup\$

bc, 9 bytes

n*(n+1)/2

Try it online!

Weird how some shell solutions call bc instead of just writing bc code.

\$\endgroup\$
2
\$\begingroup\$

Fortran (GFortran), 35 28 bytes

Try it online!

read*,n;print*,n*(n+1)/2;end

Old (but kinda fun) solution: Construct inline anonymous array, sum, and print.

read*,n;print*,sum([(j,j=1,n)]);end
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

Swift, 13 bytes

Anonymous function:

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

You can call it like this:

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Mathematica, 9 bytes

#(#+1)/2&

or, at 11 bytes,

Tr@Range@#&
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ Are you sure about the - operator? \$\endgroup\$ Commented Jul 18, 2017 at 22:36
  • \$\begingroup\$ @OlivierGrégoire Sure that it's the subtraction operator? I'm as sure as the AHK docs are \$\endgroup\$
    – Mayube
    Commented Jul 18, 2017 at 22:38
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jul 18, 2017 at 22:44
  • \$\begingroup\$ @OlivierGrégoire Oh right yeah no I'm a turd that's supposed to be a + \$\endgroup\$
    – Mayube
    Commented Jul 18, 2017 at 22:53
1
\$\begingroup\$

Tcl, 27 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Casio Basic, 9 bytes

(n+1)n/2

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

\$\endgroup\$
1
\$\begingroup\$

Factor, 12 bytes

[ iota sum ]

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

\$\endgroup\$
1
\$\begingroup\$

Terrapin Logo, 16 bytes

OP (1+:N)*(:N/2)
\$\endgroup\$
1
\$\begingroup\$

Commentator, 22 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

GolfScript, 7 6 bytes

~.)2/*

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Pip, 7 bytes

a*++a/2

Try it online!

\$\endgroup\$
1
\$\begingroup\$

><>, 20 15 bytes

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

@notatree saved me a couple bytes!

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – Not a tree
    Commented Jul 19, 2017 at 7:42
1
\$\begingroup\$

Carrot, 9 bytes

#^F+1/2*$

Explanation:

#  //Set the string stack to the input
^  //Convert to operations mode
F  //Change to float stack
+1 //Add one to the stack
/2 //Divide the stack by 2
*$ //Multiply the stack by the input
   //Implicitly output the result
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
3
  • 1
    \$\begingroup\$ (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. \$\endgroup\$ Commented Jul 19, 2017 at 12:34
  • \$\begingroup\$ Side note: Use four spaces to format the code not back ticks. \$\endgroup\$ Commented Jul 19, 2017 at 12:34
  • \$\begingroup\$ @TheLethalCoder thanks! I just found another Java answer to this thread which indeed does it a great deal shorter and does not print ^^ \$\endgroup\$ Commented Jul 19, 2017 at 12:34
1
\$\begingroup\$

Befunge, 9 bytes

&:1+*2/.@

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Gaia, 2 bytes

+⊢

This is reduce by addition +, which implicitly casts numbers to ranges beforehand.

You could also do ┅Σ (range and sum Σ), which is still 2 bytes.

\$\endgroup\$
1
\$\begingroup\$

Common Lisp, 26 bytes

(lambda(n)(/(+(* n n)n)2))
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Hello, and welcome to the site! \$\endgroup\$
    – user58826
    Commented Jul 19, 2017 at 11:31
1
\$\begingroup\$

Clojure, 31 23 16 bytes

8 bytes saved thanks to @cliffroot

#(/(+(* % %)%)2)

Try it online!

\$\endgroup\$
0
1
\$\begingroup\$

Excel VBA, 14 Bytes

Anonymous VBE immediate window function that takes input from range [A1] and outputs to the VBE immediate window

?[A1*(A1+1)/2]
\$\endgroup\$
1
\$\begingroup\$

Java, 10 bytes

n->n*-~n/2

Admittedly, only slightly different from another Java answer, but uses two's complement trickery.

\$\endgroup\$
1
\$\begingroup\$

Ly, 26 7 bytes

n:1+*2/u

EDIT: Saved a bunch of bytes by using a far better algorithm.

\$\endgroup\$
1 2 3
4
5
8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.