63
\$\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\$
  • 5
    \$\begingroup\$ Closely related \$\endgroup\$ – FryAmTheEggman Jul 18 '17 at 20:36
  • \$\begingroup\$ @FryAmTheEggman Sorry - had a bit of a brain fart there. I see what you mean. \$\endgroup\$ – GarethPW Jul 18 '17 at 20:45
  • 2
    \$\begingroup\$ @Aaron you got ninja'd by Husk, which was just posted with a 1 byte solution \$\endgroup\$ – Skidsdev Jul 18 '17 at 21:35
  • 7
    \$\begingroup\$ I suggest a stack snippet. \$\endgroup\$ – programmer5000 Jul 19 '17 at 11:42
  • 1
    \$\begingroup\$ Related: minecraftforum.net/forums/off-topic/… \$\endgroup\$ – Jerry Jeremiah Jul 27 '17 at 12:20

150 Answers 150

0
\$\begingroup\$

Swift 3, 60 Bytes

var b=Int.init(readLine()!)!
(1..<b).forEach{b+=$0}
print(b)

Try it online!

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

Matlab/Octave, 12 bytes

@(n)sum(1:n)
\$\endgroup\$
0
\$\begingroup\$

Perl 5, 11 bytes

10 bytes of code + 1 for -p

$_*=$_++/2

Try it online!

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

Math++, 13 bytes

?>n
(n*n+n)/2
\$\endgroup\$
0
\$\begingroup\$

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

Python 3, 35 bytes

print(sum(range(1,int(input())+1)))
\$\endgroup\$
0
\$\begingroup\$

Implicit, 2 bytes

¡Þ

Try it online!

    implicit integer input
¡   push 1..n
 Þ  add stack together
    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
\$\endgroup\$
0
\$\begingroup\$

C (gcc) 16 bytes

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

Try it online

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

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!

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

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
       ADD T TO R
       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).

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

Windows batch, 57 21 bytes

Inspired by J42161217

@cmd/cset/a%1*(%1+1)/2
\$\endgroup\$
0
\$\begingroup\$

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

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

Broccoli, 35, 33 bytes

(fn t ($n) (/ (* $n (+ 1 $n)) 2))

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

(t 10)
\$\endgroup\$
  • \$\begingroup\$ Surely n*(n+1)/2 should be shorter, even in this ridiculous language \$\endgroup\$ – Mego Jan 12 '18 at 5:25
  • \$\begingroup\$ @Mego Surprisingly, not by very much. And it outputs it as a float, not an int. I hope that's OK. \$\endgroup\$ – DJMcMayhem Jan 12 '18 at 5:37
  • 2
    \$\begingroup\$ I don't see why outputting as a float wouldn't be valid. There's a JS answer already. \$\endgroup\$ – Mego Jan 12 '18 at 5:38
  • \$\begingroup\$ (fn t($n)(/(* $n(+ 1 $n))2)) works too \$\endgroup\$ – ASCII-only Mar 16 '18 at 0:38
0
\$\begingroup\$

Kotlin, 13 bytes

{it*(it+1)/2}

Beautified

{
    it * (it + 1) / 2
}

Test

var f: (Int) -> Unit =
{it*(it+1)/2}

fun main(args: Array<String>) {
    println(f(5))
}

TIO

TryItOnline

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

Pyt, 2 bytes

řƩ

Try it online!

implicit input
ř returns [1, 2, 3, ... , top value]
Ʃ sums top value
implicit output

golfed by mudkip

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

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!

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

Aheui (esotope), 33 bytes

방빠받반타다따반나망해

Try it online!

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

Tidy, 13 bytes

{a:[1,a]|sum}

Try it online!

Explanation

{a:[1,a]|sum} 
{a:         }    lambda with parameter `a`
   [1,a]         range from 1 to a
        |sum     sum

Same byte count: {n:n*(n+1)/2}

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

Attache, 8 bytes

Sum@1&`:

Try it online!

Explanation

This is a composition of two functions: Sum and 1&`:. First, 1&`: is a range from 1 to the input; Sum then sums the elements.

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

Tir, 4 bytes

{∟+}

Try it online!

Explanation

{∟+}    a block
 ∟      range from 1 to the input
  +     sum that range
\$\endgroup\$
0
\$\begingroup\$

Fynyl, 5 bytes

{rf+}

Try it online!

Explanation

{rf+}    block
 r       range from 1 to input
  f+     fold addition (sum)
\$\endgroup\$
0
\$\begingroup\$

Somme, 6 bytes

n:i*G.

Try it online!

Explanation

n:i*G.
n         numeric input      [n]
 :        duplicate          [n, n]
  i       increment          [n, n+1]
   *      product            [n(n+1)]
    G     halve              [n(n+1)/2]
     .    output             []
\$\endgroup\$
0
\$\begingroup\$

;#+, 19 bytes

*;(~;~*;)-~(~+~;)+p

Try it online!

Takes input in unary, outputs in decimal.

*;(~;~*;)-~(~+~;)+p
*;                     read 1 byte of input and increment it (check EOF)
   ~;~                 increment the secondary accumulator
  (   *;)              ...while there is still input
         -             set delta value to -1 (subtraction)
                           the state is now (0, N, -)
          ~(~ ~;)      for each character read
             +         subtract N from the secondary accumulator
                           (N decreases with each iteration)
                           the state is now (0, -sum, -)
                 +     subtracts sum from accumulator (0 - (-sum) = 0 + sum = sum)
                  p    print that value
\$\endgroup\$
0
\$\begingroup\$

D, 28 bytes

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

Try it online!

Alternatively, 61 bytes: import std.range;N f(N)(N n){return std.range.iota(n).sum+n;}

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

DScript, 28 bytes

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

Try it online!

Alternatively, 34 bytes: N f(N)(N n){return iota(n).sum+n;}

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

Whitespace, 71 bytes

[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S N
S _Duplicate][N
S S N
_Create_Label_LOOP][S N
T   _Swap][S S S T  N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][N
T   S S N
_If_0_Jump_to_Label_PRINT_AND_EXIT][S N
S _Duplicate][S T   S S T   S N
_Copy_2nd][T    S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_AND_EXIT][S N
N
_Discard_top][T N
S T _Print_as_integer]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Example run: input = 3

Command   Explanation                     Stack        Heap   STDIN  STDOUT  STDERR

SSSN      Push 0                          [0]
SNS       Duplicate 0                     [0,0]
TNTT      Read STDIN as integer           [0]          {0:3}  3
TTT       Retrieve input from heap 0      [3]          {0:3}
SNS       Duplicate 3                     [3,3]        {0:3}
NSSN      Create Label_LOOP               [3,3]        {0:3}
 SNT      Swap top two                    [3,3]        {0:3}
 SSSTN    Push 1                          [3,3,1]      {0:3}
 TSST     Subtract (3-1)                  [3,2]        {0:3}
 SNS      Duplicate 2                     [3,2,2]      {0:3}
 NTSSN    If 0: Jump to Label_EXIT        [3,2]        {0:3}
 SNS      Duplicate 2                     [3,2,2]      {0:3}
 STSSTSN  Copy (0-indexed) 2nd (3)        [3,2,2,3]    {0:3}
 TSSS     Add (2+3)                       [3,2,5]      {0:3}
 NSNN     Jump to Label_LOOP              [3,2,5]      {0:3}

 SNT      Swap top two                    [3,5,2]      {0:3}
 SSSTN    Push 1                          [3,5,2,1]    {0:3}
 TSST     Subtract (2-1)                  [3,5,1]      {0:3}
 SNS      Duplicate 1                     [3,5,1,1]    {0:3}
 NTSSN    If 0: Jump to Label_EXIT        [3,5,1]      {0:3}
 SNS      Duplicate 1                     [3,5,1,1]    {0:3}
 STSSTSN  Copy (0-indexed) 2nd (5)        [3,5,1,1,5]  {0:3}
 TSSS     Add (1+5)                       [3,5,1,6]    {0:3}
 NSNN     Jump to Label_LOOP              [3,5,1,6]    {0:3}

 SNT      Swap top two                    [3,5,6,1]    {0:3}
 SSSTN    Push 1                          [3,5,6,1,1]  {0:3}
 TSST     Subtract (1-1)                  [3,5,6,0]    {0:3}
 SNS      Duplicate 0                     [3,5,6,0,0]  {0:3}
 NTSSN    If 0: Jump to Label_EXIT        [3,5,6,0]    {0:3}
NSSSN     Create Label_EXIT               [3,5,6,0]    {0:3}
 SNS      Discard top                     [3,5,6]      {0:3}
 TNST     Print top (6) to STDOUT as int  [3,5]        {0:3}         6
                                                                              error

Program stops with an error: No exit found. (Although I could add three trailing newlines NNN to get rid of that error.)

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

Runic Enchantments, 8 bytes

i:1+*2,@

Try it online!

Nothing exciting here, reads input multiplies it with itself+1, divides by 2, and outputs.

Kind of feel that I should have anticipated this sort of 1-input-1-output mathematical operation and made a MathFunc (A) operation for it ("its factorial, but addition!"), but I didn't.

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

MyLang, 7 bytes

MyLang is backwards-compatible with Deadfish~ and is designed to make Deadfish~ relatively easier to program in. Unlike the existing Deadfish derivatives which extend the memory in addition to the arithmetic operators, this derivative only adds one numeric accumulator to the existing Deadfish accumulator. (Here we call the first accumulator a and the second accumulator b.)

DISCLAIMER: The name is inspired by ETHproductions' golfing language issue template. However, MyLang is not designed as a golfing language.

[ + d} 

Explanation (for visibility spaces are replaced with @)

Implicit input to accumulator a
[       While the accumulator a is nonzero:
 @      Gain control with accumulator b
  +     Add accumulator b by the value of the accumulator a
   @    Gain control with accumulator a
    d   Decrement accumulator a by 1
     }  End while loop (the end bracket ] is already used as a marker for a separate loop.)
      @ Retrieve the value of the accumulator b
After which the value in the current accumulator (accumulator a) is implicitly outputted

MyLang, 10 bytes (using the formula)

 =i* rii /

Explanation (```@`` has the same meaning as above here)

Implicit input to accumulator a
@          Gain control with accumulator b
 =         Set accumulator b as the value of accumulator a
  i        Increment accumulator b
   *       Multiply accumulator b by the value of accumulator a
    @      Gain control with accumulator a
     r     Reset accumulator a to 0
      ii   Set accumulator a to 2
        @  Gain control with accumulator b
         / Divide accumulator b by accumulator a
After which the current accumulator (accumulator b) is implicitly outputted
```
\$\endgroup\$
0
\$\begingroup\$

Gol><>, 7 bytes

I:P*2,h

Courtesy of JoKing

Try it online!

8 bytes

I::*+2,h

Try it online!

\$\endgroup\$
-3
\$\begingroup\$

Python 3, 15 bytes

sum(range(n))+n

Just a quick check:

>>> n = 6
>>> func = "sum(range(n))+n"
>>> len(func)
15
>>> eval(func)
21
\$\endgroup\$
  • 4
    \$\begingroup\$ Unfortunately, we require that all answers must include input and output, whether that be by a function or a full program. However, you may not assume that the input is saved in a variable. Therefore Try it online! is a valid version of your answer \$\endgroup\$ – caird coinheringaahing Dec 3 '17 at 19:27
  • \$\begingroup\$ This would have to be lambda x:sum(range(n))+n for the rules. \$\endgroup\$ – MilkyWay90 Apr 1 at 23:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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