68
\$\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

160 Answers 160

0
\$\begingroup\$

Tcl, 29 bytes

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

Try it online!

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

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
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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(^)
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Scala, 12 bytes

Gauss sum (12 bytes):

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

Naive version (14 bytes):

n=>1.to(n).sum
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Clojure, 28 bytes

#(apply + (range 1 (inc %)))
| improve this answer | |
\$\endgroup\$
0
\$\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

| improve this answer | |
\$\endgroup\$
  • 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\$ – TheLethalCoder Jul 19 '17 at 12:34
  • \$\begingroup\$ Side note: Use four spaces to format the code not back ticks. \$\endgroup\$ – TheLethalCoder Jul 19 '17 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\$ – Dylan Meeus Jul 19 '17 at 12:34
0
\$\begingroup\$

Clojure, 16 bytes

#(/(*(inc %)%)2)
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Groovy, 11 bytes

{it*++it/2}

Try it online!


The input is not modified by rules of Groovy clsures.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

PHP, 35 34 32 25 bytes

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

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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Save 6 bytes with $argn and -F \$\endgroup\$ – Titus Jul 26 '17 at 11:34
0
\$\begingroup\$

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!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Swift 3, 60 Bytes

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

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Matlab/Octave, 12 bytes

@(n)sum(1:n)
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Perl 5, 11 bytes

10 bytes of code + 1 for -p

$_*=$_++/2

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Math++, 13 bytes

?>n
(n*n+n)/2
| improve this answer | |
\$\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
| improve this answer | |
\$\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)))
| improve this answer | |
\$\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
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

C (gcc) 16 bytes

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

Try it online

| improve this answer | |
\$\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!

| improve this answer | |
\$\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).

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Windows batch, 57 21 bytes

Inspired by J42161217

@cmd/cset/a%1*(%1+1)/2
| improve this answer | |
\$\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..

| improve this answer | |
\$\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)
| improve this answer | |
\$\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\$ – James 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\$

Pyt, 2 bytes

řƩ

Try it online!

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

golfed by mudkip

| improve this answer | |
\$\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!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Aheui (esotope), 33 bytes

방빠받반타다따반나망해

Try it online!

| improve this answer | |
\$\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}

| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Tir, 4 bytes

{∟+}

Try it online!

Explanation

{∟+}    a block
 ∟      range from 1 to the input
  +     sum that range
| improve this answer | |
\$\endgroup\$

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.