Sum of all integers from 1 to n

66

12

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>

GarethPW

Posted 2017-07-18T20:32:14.660

Reputation: 1 119

5Closely related – FryAmTheEggman – 2017-07-18T20:36:02.960

@FryAmTheEggman Sorry - had a bit of a brain fart there. I see what you mean. – GarethPW – 2017-07-18T20:45:22.930

I expected a bunch of very short answers (10 or 15 bytes) all either using the summation formula or a language summation feature. But DANG! A bunch of them at 2 bytes!? Is this now the "golf of code golfs," or have there been any others with 2-byte solutions (or what about 1 byte)? – Aaron – 2017-07-18T21:34:56.107

2@Aaron you got ninja'd by Husk, which was just posted with a 1 byte solution – Skidsdev – 2017-07-18T21:35:59.053

@Mayube Wow.... I originally thought this was a silly question, "It's just going to be a bunch of different languages typing out the summation formula, or if it's built in then doing sum(x); why would someone bother writing such a silly so-called golf?" But now I don't know what to say. I have been schooled. I will +1 this question after all. – Aaron – 2017-07-18T23:12:19.163

@steenbergh Working on it right now. – GarethPW – 2017-07-19T10:57:46.590

7I suggest a stack snippet. – programmer5000 – 2017-07-19T11:42:33.153

@programmer5000, steenbergh I've added the leaderboard snippet. Thanks for your suggestions! – GarethPW – 2017-07-19T19:30:02.793

@JerryJeremiah how? – FantaC – 2017-12-11T15:59:33.027

Answers

47

Pyth, 2 bytes

sS

Try it online! Implicit input. S is 1-indexed range, and s is the sum.

Jim

Posted 2017-07-18T20:32:14.660

Reputation: 1 442

109Finally, Pyth(on) code sounds like a snake. – totallyhuman – 2017-07-18T21:15:25.107

2This is the perfect challenge for Pyth... – Mr. Xcoder – 2017-07-18T22:09:19.643

I was going to answer this, but I guess not – Stan Strum – 2017-09-07T03:41:36.413

33

Husk, 1 byte

Σ

Try it online!

Builtin! Σ in Husk is usually used to get the sum of all elements of a list, but when applied to a number it returns exactly n*(n+1)/2.

Leo

Posted 2017-07-18T20:32:14.660

Reputation: 8 482

1Out of curiosity, does this occur because the number is cast to a range and then summed, or is this actually hardcoded? – FryAmTheEggman – 2017-07-18T21:33:46.743

5@FryAmTheEggman this is actually hardcoded, and is similar to the behavior of another builtin, Π, which can compute the product of all elements of a list or the factorial of a single number – Leo – 2017-07-18T21:37:09.763

4Σ is a two byte unicode character on my machine. I guess you use code page 1253? https://msdn.microsoft.com/en-us/library/cc195055.aspx – gmatht – 2017-07-19T02:32:04.180

6

@gmatht Husk's code page

– Jonathan Allan – 2017-07-19T03:02:31.717

22

Piet, 161 bytes / 16 codels

You can interpret it with this Piet interpreter or upload the image on this website and run it there. Not sure about the byte count, if I could encode it differently to reduce size.

Scaled up version of the source image:

rapapaing-image

Explanation

The highlighted text shows the current stack (growing from left to right), assuming the user input is 5:

1st transition Input a number and push it onto stack

5

2nd transition Duplicate this number on the stack

5 5

3rd transition Push 1 (the size of the dark red area) onto stack

5 5 1

4th transition Add the top two numbers

5 6

5th transition Multiply the top two numbers

30

6th transition The black area makes sure, that the cursor moves down right to the light green codel. That transition pushes 2 (the size of dark green) onto stack

30 2

7th transition Divide the second number on the stack by the first one

15

8th transition Pop and output the top number (interpreted as number)

[empty]

final trap By inserting a white area, the transition is a nop, the black traps our cursor. This ends execution of the program.

Original file (far too small for here): Original source image

ბიმო

Posted 2017-07-18T20:32:14.660

Reputation: 15 345

We transitioned from an intelligible text (e.g. C) to unintelligible text (e.g. Jelly) to images... What next? :P – frarugi87 – 2017-07-24T07:32:15.080

2+1 I haven't actually seen a Piet answer with an explanation before – MilkyWay90 – 2019-04-01T23:01:07.987

21

Brain-Flak, 16 bytes

({({}[()])()}{})

Try it online!

This is one of the few things that brain-flak is really good at.

Since this is one of the simplest things you can do in brain-flak and it has a lot of visibility, here's a detailed explanation:

# Push the sum of all of this code. In brain-flak, every snippet also returns a
# value, and all values inside the same brackets are summed
(
    # Loop and accumulate. Initially, this snippet return 0, but each time the
    # loop runs, the value of the code inside the loop is added to the result.
    {
        # Push (and also return)...
        (
            # The value on top of the stack
            {}

            # Plus the negative of...
            [
                # 1
                ()
            ]

        # The previous code pushes n-1 on to the stack and returns the value n-1
        )

        # 1
        # This code has no side effect, it just returns the value 1 each loop.
        # This effectively adds 1 to the accumulator
        ()

    # The loop will end once the value on top of the stack is 0
    }

    # Pop the zero off, which will also add 0 to the current value
    {}

# After the sum is pushed, the entire stack (which only contains the sum)
# will be implicitly printed.
)

James

Posted 2017-07-18T20:32:14.660

Reputation: 54 537

20

Oasis, 3 bytes

n+0

Try it online!

How it works

n+0
  0    a(0)=0
n+     a(n)=n+a(n-1)

Leaky Nun

Posted 2017-07-18T20:32:14.660

Reputation: 45 011

31And here I was, all of my life thinking that n+0 is n... – Wojowu – 2017-07-19T07:22:44.680

18

Mathematica, 9 bytes

#(#+1)/2&

Mathematica, 10 bytes

(#^2+#)/2&

Mathematica, 11 bytes

Tr@Range@#&

Mathematica, 12 bytes

i~Sum~{i,#}&

Mathematica, 14 bytes

(by @user71546)

1/2/Beta[#,2]&

Mathematica, 15 bytes

Tr[#&~Array~#]&

Mathematica, 16 bytes

Binomial[#+1,2]&

Mathematica, 17 bytes

(by @Not a tree)

⌊(2#+1)^2/8⌋&

Mathematica, 18 bytes

PolygonalNumber@#&

Mathematica, 19 bytes

#+#2&~Fold~Range@#&

Mathematica, 20 bytes

(by @Not a tree)

f@0=0;f@i_:=i+f[i-1]

J42161217

Posted 2017-07-18T20:32:14.660

Reputation: 15 931

4It seems a shame to skip 13, 14 and 17… – Not a tree – 2017-07-19T00:48:56.420

3It seems like a next challenge....or at least help me to complete the list. – J42161217 – 2017-07-19T00:51:11.563

You can have f@0=0;f@i_:=i+f[i-1] for 20 bytes, although that doesn't help fill the holes. – Not a tree – 2017-07-19T00:52:26.823

I will add it because it differs! – J42161217 – 2017-07-19T00:55:17.603

17 bytes: ⌊(2#+1)^2/8⌋& (inspired by the OEIS page)

– Not a tree – 2017-07-19T01:24:44.030

…or if you don't like non-ASCII characters, Tr[Range@#^3]^.5& – Not a tree – 2017-07-19T02:18:31.560

2

I still don't have anything for 13 or 14 bytes (apart from just un-golfing your shorter answers), but here are another 26 with larger byte-counts.

– Not a tree – 2017-07-19T07:16:17.390

PolygonalNumber doesn't seem to do anything in my version (10.2) of Mathematica. Do you need to import something? – Mark S. – 2017-07-25T10:54:51.667

1@MarkS. on 10.4 works fine – J42161217 – 2017-07-25T10:56:54.347

1@Notatree For your list, here is a candidate for 35: Array[Boole[#2>=#]&,{#,#}]~Total~2& – Mark S. – 2017-08-12T05:07:00.623

Also 9 bytes: Tr@*Range – ngenisis – 2017-11-02T04:41:04.077

14 bytes: 1/2/Beta[#,2]& By reference Beta[x,y] = Gamma[x] * Gamma[y] / Gamma[x+y], so dividing 1/2 by Beta[#,2] gives (#+1)!/(2*(#-1)!), which is the desired result.

– Shieru Asakoto – 2017-12-11T03:57:02.350

@user71546 very nice! thanks – J42161217 – 2017-12-11T11:34:04.950

17

JavaScript (ES6), 10 bytes

n=>n*++n/2

Example

let f =

n=>n*++n/2

console.log(f(5))

Arnauld

Posted 2017-07-18T20:32:14.660

Reputation: 111 334

3n*-~n/2 also works, but only for n < 2**31 – Patrick Roberts – 2017-12-03T18:53:44.163

11

x86_64 machine language (Linux), 9 8 bytes

0:   8d 47 01                lea    0x1(%rdi),%eax
3:   f7 ef                   imul   %edi
5:   d1 e8                   shr    %eax
7:   c3                      retq 

To Try it online! compile and run the following C program.

#include<stdio.h>
const char f[]="\x8d\x47\x01\xf7\xef\xd1\xe8\xc3";
int main(){
  for( int i = 1; i<=10; i++ ) {
    printf( "%d %d\n", i, ((int(*)())f)(i) );
  }
}

Thanks to @CodyGray and @Peter for -1.

ceilingcat

Posted 2017-07-18T20:32:14.660

Reputation: 5 503

1

You should probably use shr instead of sar, to treat your output as unsigned (no change in code size). (Spotted by @CodyGray and pointed out in his 7-byte add+loop answer).

– Peter Cordes – 2017-07-22T08:36:01.173

1

This looks optimal for performance in an implementation of the closed-form formula, but you can save a byte by using the one-operand form of mul %edi or imul %edi (each 2B) instead of the 3B two-operand form. It clobbers EDX with the high-half result, but that's fine. Multi-operand imul was introduced later than the one-operand form, and has a 2-byte opcode with a 0F escape byte. Any of the three options will always produce the same result in eax, it's only the high half that depends on signed vs. unsigned.

– Peter Cordes – 2017-07-22T08:36:47.357

10

Python 2, 24 16 bytes

-8 bytes thanks to FryAmTheEggman.

lambda n:n*-~n/2

Try it online!

totallyhuman

Posted 2017-07-18T20:32:14.660

Reputation: 15 378

10

C# (.NET Core), 10 bytes

n=>n++*n/2

Try it online!

Charlie

Posted 2017-07-18T20:32:14.660

Reputation: 11 448

10

Octave, 22 19 bytes

Because arithmetic operations are boring...

@(n)nnz(triu(e(n)))

Try it online!

Explanation

Given n, this creates an n×n matrix with all entries equal to the number e; makes entries below the diagonal zero; and outputs the number of nonzero values.

Luis Mendo

Posted 2017-07-18T20:32:14.660

Reputation: 87 464

Is this actually shorter than the numerical version? – Esolanging Fruit – 2017-07-23T15:26:43.860

@Challenger5 No, But the numerical version is boring: @(n)sum(1:n) – Luis Mendo – 2017-07-23T15:52:29.007

2

Or 16 bytes with arithmetic operations, but no sum.

– Stewie Griffin – 2017-08-06T17:35:18.717

10

Java (OpenJDK 8), 10 bytes

n->n++*n/2

Try it online!

Olivier Grégoire

Posted 2017-07-18T20:32:14.660

Reputation: 10 647

8

Haskell, 13 bytes

This is the shortest (I thinkthought):

f n=sum[1..n]

Try it online!

Direct, 17 13 bytes

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

Thanks @WheatWizard for -4 bytes!

Try it online!

Pointfree direct, 15 bytes

(*)=<<(/2).(+1)

Thanks @nimi for the idea!

Try it online!

Pointfree via sum, 16 bytes

sum.enumFromTo 1

Try it online!

Recursively, 22 18 bytes

f 0=0;f n=n+f(n-1)

Thanks @maple_shaft for the idea & @Laikoni for golfing it!

Try it online!

Standard fold, 19 bytes

f n=foldr(+)0[1..n]

Try it online!

ბიმო

Posted 2017-07-18T20:32:14.660

Reputation: 15 345

8

Jelly, 2 bytes

RS

Try it online!

Explanation

RS

    implicit input
 S  sum of the...
R   inclusive range [1..input]
    implicit output

Gauss sum, 3 bytes

‘×H

Explanation

‘×H

     implicit input
  H  half of the quantity of...
‘    input + 1...
 ×   times input
     implicit output

totallyhuman

Posted 2017-07-18T20:32:14.660

Reputation: 15 378

This also works in Anyfix :P (not on TIO) – HyperNeutrino – 2017-07-18T21:08:47.990

8

APL, 3 bytes

+/⍳

Try it online!

+/ - sum (reduce +), - range.

Uriel

Posted 2017-07-18T20:32:14.660

Reputation: 11 708

This depends on the indexing. If indexing is set to 0, then you'd need an additional 2 bytes 1+ – Werner – 2017-07-18T21:27:24.537

2@Werner indexing is default 1 so I didn't specify. its common here to specify only when using ⎕IO←0 (and it does not included in byte count) – Uriel – 2017-07-18T21:29:27.137

7

05AB1E, 2 bytes

LO

Try it online!

How it works

     #input enters stack implicitly
L    #pop a, push list [1 .. a]
 O   #sum of the list
     #implicit output 

Gauss sum, 4 bytes

>¹*;

Try it online!

How it works

>       #input + 1
 ¹*     #get original input & multiply
   ;    #divide by two 

space junk

Posted 2017-07-18T20:32:14.660

Reputation: 305

3ÝO also works and means hello. – Magic Octopus Urn – 2017-07-19T15:01:01.990

2L0 and behold.. – dylnan – 2017-12-11T16:16:45.907

7

Starry, 27 22 bytes

5 bytes saved thanks to @miles!

, + +  **       +   *.

Try it online!

Explanation

,             Read number (n) from STDIN and push it to the stack
 +            Duplicate top of the stack
 +            Duplicate top of the stack
  *           Pop two numbers and push their product (n*n)
*             Pop two numbers and push their sum (n+n*n)
       +      Push 2
   *          Pop two numbers and push their division ((n+n*n)/2)
.             Pop a number and print it to STDOUT

Luis Mendo

Posted 2017-07-18T20:32:14.660

Reputation: 87 464

22 bytes. – miles – 2017-07-18T23:20:40.853

@miles Thanks! Very good idea! – Luis Mendo – 2017-07-18T23:53:35.877

7

Check, 5 bytes

:)*$p

Check isn't even a golfing language, yet it beats CJam!

Try it online!

Explanation:

The input number is placed on the stack. : duplicates it to give n, n. It is then incremented with ), giving n, n+1. * multiplies the two together, and then $ divides the result by 2. p prints the result and the program terminates.

Esolanging Fruit

Posted 2017-07-18T20:32:14.660

Reputation: 13 542

7

Java (OpenJDK 8), 10 bytes

a->a++*a/2

Try it online!

Took a moment to golf down from n->n*(n+1)/2 because I'm slow.

But this isn't a real Java answer. It's definitely not verbose enough.

import java.util.stream.*;
a->IntStream.range(1,a+1).sum()

Not bad, but we can do better.

import java.util.stream.*;
(Integer a)->Stream.iterate(1,(Integer b)->Math.incrementExact(b)).limit(a).reduce(0,Integer::sum)

I love Java.

Xanderhall

Posted 2017-07-18T20:32:14.660

Reputation: 1 236

1If you want it to be even more verbose why use a lambda!? :P – TheLethalCoder – 2017-07-19T12:36:32.310

2I was aiming for verbose lambdas, I could write a full program if I wanted to be particularly eloquent :P – Xanderhall – 2017-07-19T12:38:46.110

1The exact same solution was already posted – Winter – 2017-07-19T18:56:01.660

2I must have missed it, but in any case, I tend to not look at the contents of other answers. I prefer to write my own golf. – Xanderhall – 2017-07-20T11:21:07.217

6

MATL, 2 bytes

:s

Try it online!

Not happy smiley.

AlexRacer

Posted 2017-07-18T20:32:14.660

Reputation: 979

2Damn it, finally a challenge I could easily answer in MATL, but you beat me to it :( – Lui – 2017-07-19T06:27:27.950

6

Taxi, 687 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l 2 r.[a]Pickup a passenger going to Addition Alley.Pickup a passenger going to The Underground.Go to Zoom Zoom:n.Go to Addition Alley:w 1 l 1 r.Pickup a passenger going to Addition Alley.Go to The Underground:n 1 r 1 r.Switch to plan "z" if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 3 l 2 l.Switch to plan "a".[z]Go to Addition Alley:n 3 l 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

Try it online!

Un-golfed with comments:

[ n = STDIN ]
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left 1st left 2nd right.

[ for (i=n;i>1;i--) { T+=i } ]
[a]
Pickup a passenger going to Addition Alley.
Pickup a passenger going to The Underground.
Go to Zoom Zoom: north.
Go to Addition Alley: west 1st left 1st right.
Pickup a passenger going to Addition Alley.
Go to The Underground: north 1st right 1st right.
Switch to plan "z" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 3rd left 2nd left.
Switch to plan "a".

[ print(T) ]
[z]
Go to Addition Alley: north 3rd left 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: north 1st right 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.

It's 22.6% less bytes to loop than it is to use x*(x+1)/2

Engineer Toast

Posted 2017-07-18T20:32:14.660

Reputation: 5 769

5

,,,, 6 bytes

:1+×2÷

Explanation

:1+×2÷

:       ### duplicate
 1+     ### add 1
   ×    ### multiply
    2÷  ### divide by 2

If I implement range any time soon...

totallyhuman

Posted 2017-07-18T20:32:14.660

Reputation: 15 378

5

Julia, 10 bytes

n->n*-~n/2

Try it online!

11 bytes (works also on Julia 0.4)

n->sum(1:n)

Try it online!

Uriel

Posted 2017-07-18T20:32:14.660

Reputation: 11 708

5

Brainfuck, 24 Bytes.

I/O is handled as bytes.

,[[->+>+<<]>[-<+>]<-]>>.

Explained

,[[->+>+<<]>[-<+>]<-]>>.
,                           # Read a byte from STDIN
 [                  ]       # Main loop, counting down all values from n to 1
  [->+>+<<]                 # Copy the i value to *i+1 and *i+2
           >[-<+>]          # Move *i+1 back to i
                  <-        # Move back to i, lower it by one. Because *i+2 is never reset, each iteration adds the value of i to it.
                     >>.    # Output the value of *i+2

ATaco

Posted 2017-07-18T20:32:14.660

Reputation: 7 898

2It's pretty cool that Brainfuck is able to beat some higher-level languages in this challenge. – GarethPW – 2017-07-19T10:49:29.510

Is that legit for me to add an answer in Lenguage (just for fun) using your code? @ATaco – V. Courtois – 2017-07-26T12:44:05.617

I don't think so, as it would be the same code, just encoded different. @V.Courtois – ATaco – 2017-07-26T13:07:49.167

@ATaco Ahh you're right. – V. Courtois – 2017-07-26T13:19:06.933

5

dc, 7 bytes

d1+*2/p

OR

d2^+2/p

OR

dd*+2/p

Try it online!

Maxim Mikhaylov

Posted 2017-07-18T20:32:14.660

Reputation: 571

4

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

Chaos Manor

Posted 2017-07-18T20:32:14.660

Reputation: 521

3Actually, I think you saved 9 bytes thanks to Gauss ;) But thanks for the credit! – FryAmTheEggman – 2017-07-18T21:10:45.763

4

><>, 7+3 = 10 bytes

Calculates n(n+1)/2.
3 bytes added for the -v flag

:1+2,*n

Try it online!

Or if input can be taken as a character code:

><>, 9 bytes

i:1+2,*n;

Try it online!

Emigna

Posted 2017-07-18T20:32:14.660

Reputation: 50 798

2Using the other math-approach ((n^2+n)/2) is also 7 bytes: ::*+2,n – steenbergh – 2017-07-19T08:18:49.750

4

Retina, 13 bytes

.+
$*
1
$`1
1

Try it online! Explanation: The first and last stages are just unary ⇔ decimal conversion. The middle stage replaces each 1 with the number of 1s to its left plus another 1 for the 1 itself, thus counting from 1 to n, summing the values implicitly.

Neil

Posted 2017-07-18T20:32:14.660

Reputation: 95 035

4

PHP, 19 bytes

<?=$argn*-~$argn/2;
<?=$argn/2*++$argn;
<?=$argn*++$argn/2; # this one fails

using builtins, 29 bytes:

<?=array_sum(range(1,$argn));

loop, 31 bytes:

while($argn)$s+=$argn--;echo$s;

Titus

Posted 2017-07-18T20:32:14.660

Reputation: 13 814

I guess a for too: for(;$argn;$s+=$argn--);echo$s; – Progrock – 2019-10-13T17:12:04.167

4

x86-64 Machine Code, 7 bytes

31 C0
01 C8
E2 FC
C3  

The above bytes define a function that accepts a single parameter, n, and returns a value containing the sum of all integers from 1 to n.

It is written to the Microsoft x64 calling convention, which passes the parameter in the ECX register. The return value is left in EAX, like all x86/x86-64 calling conventions.

Ungolfed assembly mnemonics:

       xor  eax, eax    ; zero out EAX
Next:  add  eax, ecx    ; add ECX to EAX
       loop Next        ; decrement ECX by 1, and loop as long as ECX != 0
       ret              ; return, with result in EAX

Try it online!
(The C function call there is annotated with an attribute that causes GCC to call it using the Microsoft calling convention that my assembly code uses. If TIO had provided MSVC, this wouldn't be necessary.)


By the unusual standards of code golf, you see that this iterative looping approach is preferable to approaches that use the more sane mathematical formula (n(n+1) / 2), even though it is obviously vastly less efficient in terms of run-time speed.

Using number theory, ceilingcat's implementation can still be beat by one byte. Each of these instructions are essential, but there is a slightly shorter encoding for IMUL that uses EAX implicitly as a destination operand (actually, it uses EDX:EAX, but we can just ignore the upper 32 bits of the result). This is only 2 bytes to encode, down from 3.

LEA takes three bytes as well, but there's really no way around that because we need to increment while preserving the original value. If we did a MOV to make a copy, then INC, we'd be at 4 bytes. (In x86-32, where INC is only 1 byte, we'd be at the same 3 bytes as LEA.)

The final right-shift is necessary to divide the result in half, and is certainly more compact (and more efficient) than a multiplication. However, the code should really be using shr instead of sar, since it's assuming that the input value, n, is an unsigned integer. (That assumption is valid according to the rules, of course, but if you know that the input is unsigned, then you shouldn't be doing a signed arithmetic shift, as the upper bit being set in a large unsigned value will cause the result to be incorrect.)

8D 41 01                lea    eax, [rcx+1]
F7 E9                   imul   ecx
D1 E8                   shr    eax, 1
C3                      ret

Now only 8 bytes (thanks to Peter Cordes). Still, 8 > 7.

Cody Gray

Posted 2017-07-18T20:32:14.660

Reputation: 2 639

1Actually, one-operand imul ecx or mul ecx would work and save a byte in the closed-form implementation. I didn't spot that right away; I was about to comment that it was optimal for both performance and code-size before realizing that an implicit eax operand was fine. – Peter Cordes – 2017-07-22T08:42:27.213

I wondered if add+loop would be shorter than imul while looking at the other answer. Handy that there's a standard calling convention that passes the first arg in ecx – Peter Cordes – 2017-07-22T08:45:47.883

1Wow, I can't believe I missed the one-operand form! I should really know by now not to say things like "cannot be beat". When will I learn?! Thanks, @Peter. – Cody Gray – 2017-07-22T11:08:07.693

4

Cubix, 12 10 bytes

*,)2I://O@

Initial version

....I:)*2,O@

Try it online!

Explanation

Expanded onto a cube, the code looks like this:

    * ,
    ) 2
I : / / O @ . .
. . . . . . . .
    . .
    . .

The instruction pointer (IP) starts at the I, moving east. It continues moving east until it comes across the / mirror, which reflects it north. When the IP reaches the top of the code, it wraps around to the last . on the third line, moving south. Then it wraps to the penultimate . on the last line, moving north. Then it reaches the / mirror again, which reflects it east, only for the next / to reflect it north again. This time, the IP wraps to the penultimate . on the third line, and then the last . on the last line.

The instructions are executed in the following order.

I:)*2,O@ # Explanation
I        # Take input as an integer and push it to the stack
 :       # Duplicate the input
  )      # Increment one of the inputs
   *     # Multiply the input by input+1
    2    # Push 2 to the stack
     ,   # Integer devide the multiplication result by 2
      O  # Output the result
       @ # End program

Luke

Posted 2017-07-18T20:32:14.660

Reputation: 4 675

4

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.

user41805

Posted 2017-07-18T20:32:14.660

Reputation: 16 320

4

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!

fxwang

Posted 2017-07-18T20:32:14.660

Reputation: 41

3

Ohm, 2 bytes

Try it online!

Explanation

@Σ

    implicit input
@   inclusive range [1..input]
 Σ  sum
    implicit output

totallyhuman

Posted 2017-07-18T20:32:14.660

Reputation: 15 378

3

Ruby, 29 17 18 14 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!

Snaddyvitch Dispenser

Posted 2017-07-18T20:32:14.660

Reputation: 101

2Wouldn't this be shorter with a different name? Like s instead of sum? Also, I think you could remove some spaces – James – 2017-07-18T21:14:18.733

Yep, just submitted it for speed, thanks for the notice! – Snaddyvitch Dispenser – 2017-07-18T21:15:40.250

1Hi 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 – 2017-07-18T21:28:27.557

@FryAmTheEggman Thanks, You Saved Me 6 Bytes! I have also amended the input code so that it will accept input properly. Just about to post the update! – Snaddyvitch Dispenser – 2017-07-18T21:52:25.147

2You 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 – 2017-07-18T21:56:18.513

3You 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 – 2017-07-18T23:31:36.253

Value ink, thanks! – Snaddyvitch Dispenser – 2017-07-23T14:44:09.220

You can save another 2 bytes by using -~n instead of (n+1) – G B – 2018-01-12T07:08:21.393

3

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

Stephen

Posted 2017-07-18T20:32:14.660

Reputation: 12 293

3

WendyScript, 17 bytes

<<f=>(x)x*(x+1)/2

f(100) // => 5050

Try it online!

Felix Guo

Posted 2017-07-18T20:32:14.660

Reputation: 211

3

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.

Skidsdev

Posted 2017-07-18T20:32:14.660

Reputation: 9 656

Isn't there decrement peg? I'm pretty sure it is either ) or ( – Roman Gräf – 2017-07-19T08:00:15.107

@RomanGräf I literally used that peg in another challenge like 5 minutes before writing this answer, I'm an idiot :P – Skidsdev – 2017-07-19T08:32:16.787

I also forgot that despite being typeable on my UK keyboard layout, £ is not a 1-byte character. Changed division character to , – Skidsdev – 2017-07-19T08:35:42.480

I don't thinm editing the name of a feature after the realese of the challenge is valid tho... – Roman Gräf – 2017-07-19T08:36:57.957

@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 – 2017-07-19T09:07:56.010

3

Bash, 26, 19 bytes

echo $[($1+1)*$1/2]

Try it online!

19 bytes for the code, thanks to rexkogitans.

Ivan Botero

Posted 2017-07-18T20:32:14.660

Reputation: 301

1echo $[($1+1)*$1/2] 19 bytes – rexkogitans – 2017-07-19T16:32:19.770

@rexkogitans Edited! Thanks – Ivan Botero – 2017-07-21T16:34:07.240

3

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;
}

Keyu Gan

Posted 2017-07-18T20:32:14.660

Reputation: 2 028

3

Brachylog, 2 bytes

⟦+

Try it online!

Explanation

⟦      Range: [0, …, Input]
 +     Sum:   0 + … + Input

Fatalize

Posted 2017-07-18T20:32:14.660

Reputation: 32 976

3

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

Agent_Meerkat

Posted 2017-07-18T20:32:14.660

Reputation: 31

2

Welcome to the site! Nice first golf! You may be interested in some tips for golfing in C.

– programmer5000 – 2017-07-19T11:24:32.447

3

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.

João the Clown

Posted 2017-07-18T20:32:14.660

Reputation: 31

1Welcome to PPCG! – Stephen – 2017-07-19T13:04:36.673

3

Python 2, 16 bytes

lambda n:-~n*n/2

Try it online!

Rohit-Pandey

Posted 2017-07-18T20:32:14.660

Reputation: 169

2Welcome to PPCG! – Martin Ender – 2017-07-19T16:56:04.970

Is there any problem in my answer? – Rohit-Pandey – 2017-07-19T17:03:16.570

1You 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ý – 2017-07-19T17:22:25.620

Thank you, sir but what is PPCG? – Rohit-Pandey – 2017-07-19T17:28:32.270

This community. Programming Puzzles & Code Golf. – Martin Ender – 2017-07-19T17:30:16.490

3Where is n defined? – Eric Duminil – 2017-07-20T08:59:42.193

Here n is Input. – Rohit-Pandey – 2017-07-20T16:19:53.187

6Our 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 – 2017-07-20T18:27:14.700

3

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.

MD XF

Posted 2017-07-18T20:32:14.660

Reputation: 11 605

3

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

user1812

Posted 2017-07-18T20:32:14.660

Reputation: 101

You might want to make TI-BASIC link to something. – Zacharý – 2017-07-30T17:52:07.593

TI-BASIC is the language that is used on most Texas instruments graphics calculators; what should I link to? – user1812 – 2017-07-31T18:40:18.690

Or remove the brackets. – Zacharý – 2017-07-31T18:48:58.760

Alternatively sum(randIntNoRep(1,N – Oki – 2017-09-09T11:50:04.330

Wow! Didnt think of that :D It is unfortunate that randIntNoRep() is 2 bytes not 1. – user1812 – 2017-09-09T22:37:18.720

3

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

Timtech

Posted 2017-07-18T20:32:14.660

Reputation: 12 038

Why not sum(randIntNoRep(1,Ans? – lirtosiast – 2017-08-25T00:33:58.547

@lirtosiast True, that didn't occur to me. – Timtech – 2017-08-25T02:21:08.887

3

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 

Jerry

Posted 2017-07-18T20:32:14.660

Reputation: 71

3

Symbolic Python, 35 33 18 16 bytes

_=-~_*_/-~(_==_)

Try it online!

Uses the direct formula for triangle numbers, (n+1)(n/2):

_=                  # Set output to
  -~_               #   (n+1)
     *_             #   *n
       /-~(_==_)    #   /2

FlipTack

Posted 2017-07-18T20:32:14.660

Reputation: 13 242

3

Alchemist, 40 bytes

0x+_->a+Out_I
0_+0x+a->x
x+a->_+x
x+0a->

Outputs in unary, try it online or try it with automatic conversion to decimal!

Explanation

We'll 3 types of atoms the \$\texttt{_}\$-, \$\texttt{x}\$- and \$\texttt{a}\$-atoms:

  • \$\texttt{_}\$ initially is the input
  • \$\texttt{x}\$ is to make sure the computation is deterministic
  • \$\texttt{a}\$
# When there is no x-atom but still _ left, transform it to a and output I
0x + _ -> a + Out_I
# If there are no _- and x-atoms but still at least one a, we remove one a and add an x
0_ + 0x + a -> x
# If there is an x-atom, exchange all a-atoms for _-atoms
x + a -> _ + x
# Once we're done with that, remove the x-atom (this makes the first rule applicable again, creating a loop)
x + 0a ->

So essentially we transform each \$\texttt{_}\$ to \$\texttt{a}\$ while outputting an \$\texttt{I}\$, remove one \$\texttt{a}\$ and exchange them back to \$\texttt{_}\$, until there are no \$\texttt{a}\$-atoms and no rule is applicable anymore - terminating the progress of the universe.

ბიმო

Posted 2017-07-18T20:32:14.660

Reputation: 15 345

:/ 64

– ASCII-only – 2019-01-30T09:38:50.437

2

PowerShell, 22 18 bytes

param($n)$n*++$n/2

Try it online!

Saved 4 bytes thanks to FryAmTheEggman. Uses Gauss' formula. Ho-hum.

AdmBorkBork

Posted 2017-07-18T20:32:14.660

Reputation: 41 581

@FryAmTheEggman You'd think so, and you'd be right. :p – AdmBorkBork – 2017-07-18T20:53:03.867

2

R, 13 bytes

sum(1:scan())

Saved 9 bytes thanks to Giuseppe and Max Lawnboy.

Forgottenscience

Posted 2017-07-18T20:32:14.660

Reputation: 417

1Would be shorter if you used n=scan() instead of defining a function. – Maxim Mikhaylov – 2017-07-19T02:22:44.190

4And it would be even shorter to just use sum(1:scan()) – Giuseppe – 2017-07-19T02:47:27.960

This is not a valid R code. I believe this is what you were aiming at f=function(n)sum(1:n). – djhurio – 2017-07-19T09:50:52.277

1^ 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 – 2017-07-19T10:42:17.297

It should be sum(1:scan()), not sum(1:scan(n)). – djhurio – 2017-07-19T20:59:05.483

@djhurio I don't think that'll work...pretty sure that throws an error

– Giuseppe – 2017-07-19T22:33:09.827

@Giuseppe, this is what I am saying. sum(1:scan()) is correct code. – djhurio – 2017-07-20T06:02:30.333

No it isn't, you need to handle printing in a full program.

– JAD – 2017-08-24T04:45:36.407

2

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;}

user230118

Posted 2017-07-18T20:32:14.660

Reputation: 239

4eliminate spaces: #define F(N)(n+1)*n/2, F(N){return(n+1)*n/2}; – Uriel – 2017-07-18T23:13:31.247

1And for the "code and math" section, you don't need the semicolon after the }. – Zacharý – 2017-07-19T17:23:25.980

Um ... actually the first two solutions don't work... C is case sensitive! – Zacharý – 2017-07-23T16:18:24.420

also change (n+1) to -~n: #define F(n)-~n*n/2 – dingledooper – 2019-10-17T00:17:29.607

2

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.

Explanation

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

Previous solution (6 bytes)

Explanation below

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

7 byte solutions

Explanations beneath each

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

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

cole

Posted 2017-07-18T20:32:14.660

Reputation: 3 526

2

Neim, 3 2 bytes

First Neim answer


Try it online!

Explanation

   # Gets inclusive range from 0 to input
   # Sum the list

Saved a byte due to Okx

LiefdeWen

Posted 2017-07-18T20:32:14.660

Reputation: 3 381

Nein has implicit input, so you can remove the first byte :) – Okx – 2017-07-19T08:47:31.213

@Okx I could've sworn i tried that, thanks. – LiefdeWen – 2017-07-19T08:56:16.830

2

Positron, 27 bytes

Positron is a new practical language by @HyperNeutrino.

function{return$1*($1+1)/2}

Try it online!

totallyhuman

Posted 2017-07-18T20:32:14.660

Reputation: 15 378

3Yay I'm happy :D – HyperNeutrino – 2017-07-19T01:25:17.930

2

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)

Brad Gilbert b2gills

Posted 2017-07-18T20:32:14.660

Reputation: 12 713

You can save 2 more bytes with {[+] ^$_} – Massa – 2017-09-08T14:12:23.690

@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 – 2017-09-08T15:10:45.330

2

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

aAaa aAaa

Posted 2017-07-18T20:32:14.660

Reputation: 141

2

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.

Scott

Posted 2017-07-18T20:32:14.660

Reputation: 171

2

Common Lisp, 26 bytes

(lambda(n)(/(+(* n n)n)2))

MadPhysicist

Posted 2017-07-18T20:32:14.660

Reputation: 131

2Hello, and welcome to the site! – programmer5000 – 2017-07-19T11:31:17.337

2

shortC,  44  29 bytes

Bn){K"%d",&n);R"%d",n*(n+1)/2

Try it online!

Just a shortCed version of this. Any help would be appreciated.

programmer5000

Posted 2017-07-18T20:32:14.660

Reputation: 7 828

29 bytes – None – 2019-10-12T15:02:22.077

16 bytes because functions are allowed – None – 2019-10-12T15:12:34.910

2

Vim, 4̶6̶ 25 17 16 15 keystrokes

Thanks @CowsQuack for -9 bytes!

YP<C-a>Jr*0C<C-r>=<C-r>"/2⏎

Try it online!

Ungolfed/Explained

YP                           " duplicate line containing N
  <C-a>                      " increment the first line
       J                     " join the two lines
        r*                   " substitute space between N and N+1 with *
          0C                 " delete line (store in " register) and insert
            <C-r>=        ⏎  "   the expression
                  <C-r>"     "   from the " register
                        /2   "   divided by 2

inside vim

ბიმო

Posted 2017-07-18T20:32:14.660

Reputation: 15 345

2

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.

mbomb007

Posted 2017-07-18T20:32:14.660

Reputation: 21 944

2

Röda, 13 bytes

{seq 1,_|sum}

Try it online!

fergusq

Posted 2017-07-18T20:32:14.660

Reputation: 4 867

2

ArnoldC, 301 bytes

Well if Leo can find a way to do it in one byte, this is my way of throwing in the towel.

With the language based on the guy who never surrenders.

(And studying for the precalc final, you know, n(n+1)/2 is a formula I won't forget now, right?)

As of now, there's not really a way to take input in from the console from Try It Online, but this guy supposedly added something here.

Assuming that works, this code should do:

IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP 0
GET YOUR ASS TO MARS n
DO IT NOW
WHO IS YOUR DADDY AND WHAT DOES HE DO
HEY CHRISTMAS TREE a
YOU SET US UP n
GET TO THE CHOPPER a
HERE IS MY INVITATION a
GET UP 1
YOU'RE FIRED n
HE HAD TO SPLIT 2
ENOUGH TALK
TALK TO THE HAND a
YOU HAVE BEEN TERMINATED

If not, this should work, manually assigning variable n (although it's a bit against the challenge)

IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP 3
HEY CHRISTMAS TREE a
YOU SET US UP n
GET TO THE CHOPPER a
HERE IS MY INVITATION a
GET UP 1
YOU'RE FIRED n
HE HAD TO SPLIT 2
ENOUGH TALK
TALK TO THE HAND a
YOU HAVE BEEN TERMINATED

Try it online!

bearacuda13

Posted 2017-07-18T20:32:14.660

Reputation: 834

2

Pyt, 1 byte

Try it online!

Explanation:

               implicit input
 △             compute the nth triangle number

mudkip201

Posted 2017-07-18T20:32:14.660

Reputation: 833

Can you give a link to the codepage? – Zacharý – 2017-12-24T20:11:40.067

It's at the beginning of the interpreter2 file - the language is still a work in progress – mudkip201 – 2017-12-24T20:34:55.120

I just added a link to the codepage – mudkip201 – 2018-01-12T01:11:28.993

1 byte – caird coinheringaahing – 2018-01-28T21:04:49.497

@cairdcoinheringaahing I never got around to editing all of my old answers once I made Pyt take input implicitly. I've edited some of them, but not all – mudkip201 – 2018-01-28T21:07:01.783

2

Jirka Picek

Posted 2017-07-18T20:32:14.660

Reputation: 171

2

Spice (56 bytes)

;a;b;c;d@
REA a;
ADD a 1 b;
DIV b 2 c;
MUL a c d;
OUT d;

Explanation

The code is an implementation of the n*(n+1)/2 solution seen in other responses. It should be fairly readable but here's the code annotated:

;a;b;c;d@    - Declare 4 vars a, b, c and d (@ marks end of declarations)
REA a;       - Read in the value from the console and store in a
ADD a 1 b;   - Add 1 to a and store in b
DIV b 2 c;   - Divide b by 2 and store in c
MUL a c d;   - Mulitply a and c and store in d
OUT d;       - Output d to console

Slord6

Posted 2017-07-18T20:32:14.660

Reputation: 71

1

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

user72364

Posted 2017-07-18T20:32:14.660

Reputation:

1

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

Luis Mendo

Posted 2017-07-18T20:32:14.660

Reputation: 87 464

1

Japt -x, 3 1 bytes

ò

Explanation:

ò     Range [0...Input]
-x    Sum

Try it online!

Oliver

Posted 2017-07-18T20:32:14.660

Reputation: 7 160

1

Add++, 15 9 bytes

D,f,@,Rb+

Try it online!

ಠ_ಠ I forgot about functions. And then I forgot about the range command

How it works

D,f,@,    - Create a monadic function called f (one argument)
      R   - Generate a range from 1 to n
       b+ - Reduce that range by addition (sum)

caird coinheringaahing

Posted 2017-07-18T20:32:14.660

Reputation: 13 702

1

Braingolf, 1 byte

Q

Try it online!

1-indexed (ie 7 returns 0-6 summed)

Braingolf, 3 bytes

U&+

Try it online!

U - range, &+ - sum.

Skidsdev

Posted 2017-07-18T20:32:14.660

Reputation: 9 656

1

Clojure, 31 23 16 bytes

8 bytes saved thanks to @cliffroot

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

Try it online!

Uriel

Posted 2017-07-18T20:32:14.660

Reputation: 11 708

1

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.

Skidsdev

Posted 2017-07-18T20:32:14.660

Reputation: 9 656

Are you sure about the - operator? – Olivier Grégoire – 2017-07-18T22:36:09.853

@OlivierGrégoire Sure that it's the subtraction operator? I'm as sure as the AHK docs are – Skidsdev – 2017-07-18T22:38:43.797

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. – Olivier Grégoire – 2017-07-18T22:44:19.223

@OlivierGrégoire Oh right yeah no I'm a turd that's supposed to be a + – Skidsdev – 2017-07-18T22:53:33.060

1

Swift, 13 bytes

Anonymous function:

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

You can call it like this:

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

Try it online!

Mr. Xcoder

Posted 2017-07-18T20:32:14.660

Reputation: 39 774

1

Mathematica, 9 bytes

#(#+1)/2&

or, at 11 bytes,

Tr@Range@#&

numbermaniac

Posted 2017-07-18T20:32:14.660

Reputation: 639

1

Ly, 26 7 bytes

n:1+*2/u

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

LyricLy

Posted 2017-07-18T20:32:14.660

Reputation: 3 313

1

4, 40 bytes

3.70060101002000120300026040230503045054

Try it online!

Uriel

Posted 2017-07-18T20:32:14.660

Reputation: 11 708

1

Tcl, 27 bytes

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

Try it online!

sergiol

Posted 2017-07-18T20:32:14.660

Reputation: 3 055

1

Casio Basic, 9 bytes

(n+1)n/2

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

numbermaniac

Posted 2017-07-18T20:32:14.660

Reputation: 639

1

Factor, 12 bytes

[ iota sum ]

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

cat

Posted 2017-07-18T20:32:14.660

Reputation: 4 989

1

Terrapin Logo, 16 bytes

OP (1+:N)*(:N/2)

Adrian Zhang

Posted 2017-07-18T20:32:14.660

Reputation: 199

1

GolfScript, 7 6 bytes

~.)2/*

Try it online!

Erik the Outgolfer

Posted 2017-07-18T20:32:14.660

Reputation: 38 134

1

Commentator, 22 bytes

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

Try it online!

Erik the Outgolfer

Posted 2017-07-18T20:32:14.660

Reputation: 38 134

1

><>, 20 15 bytes

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

@notatree saved me a couple bytes!

Try it online!

steenbergh

Posted 2017-07-18T20:32:14.660

Reputation: 7 772

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. – Not a tree – 2017-07-19T07:42:36.197

@Notatree Thanks! – steenbergh – 2017-07-19T07:55:18.203

1

Pip, 7 bytes

a*++a/2

Try it online!

steenbergh

Posted 2017-07-18T20:32:14.660

Reputation: 7 772

1

Javascript, 12 bytes

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

MadPhysicist

Posted 2017-07-18T20:32:14.660

Reputation: 131

1-2 bytes: n=>n*--n/2 – Herman L – 2017-07-19T17:28:48.450

Could you elaborate? :-) – MadPhysicist – 2017-07-19T18:19:54.463

1n=>n*++n/2 is the same thing as n=>n*(n+1)/2, while also changing the value of n. Since we don't need n anymore, this doesn't matter. (n=>n*--n/2 is incorrect due to a typo) – Herman L – 2017-07-20T07:40:10.333

1

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

TheLethalCoder

Posted 2017-07-18T20:32:14.660

Reputation: 6 930

1

MY, 4 bytes

Wow, MY is actually capable of something!

iΣ↵

Try it online!

Explanation (hex/cp):

1A/ - push input as an integer
49/i - pop a; push [1 .. a]
53/Σ - pop a; push sum(a)
27/↵ - pop a; print(a) (with newline)

Zacharý

Posted 2017-07-18T20:32:14.660

Reputation: 5 710

1

Befunge, 9 bytes

&:1+*2/.@

Try it online!

Vincent

Posted 2017-07-18T20:32:14.660

Reputation: 601

1

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.

Business Cat

Posted 2017-07-18T20:32:14.660

Reputation: 8 927

1

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]

Taylor Scott

Posted 2017-07-18T20:32:14.660

Reputation: 6 709

1

Java, 10 bytes

n->n*-~n/2

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

David Conrad

Posted 2017-07-18T20:32:14.660

Reputation: 1 037

1

ArnoldC, 461 bytes

IT'S SHOWTIME
HEY CHRISTMAS TREE I
YOU SET US UP 0
GET YOUR ASS TO MARS I
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
HEY CHRISTMAS TREE Z
YOU SET US UP I
GET TO THE CHOPPER I
HERE IS MY INVITATION I
GET UP 1
ENOUGH TALK
GET TO THE CHOPPER Z
HERE IS MY INVITATION Z
YOU'RE FIRED I
ENOUGH TALK
GET TO THE CHOPPER Z
HERE IS MY INVITATION Z
HE HAD TO SPLIT 2
ENOUGH TALK
TALK TO THE HAND Z
YOU HAVE BEEN TERMINATED

Explanation

Schwarzy.

Try it online!

V. Courtois

Posted 2017-07-18T20:32:14.660

Reputation: 868

1

Kona - 8 bytes

{+/!x+1}

Explanation:

 +/      Add together
   !      All numbers less than...
    x+1   The input plus 1

Alternative answer - 8 bytes:

{+/x,!x}

 +/      Add together
   x      The input
    ,     Joined to
     !     All the numbers less than...
      x    The input

kitcar2000

Posted 2017-07-18T20:32:14.660

Reputation: 2 689

If you dont need it to be a function you can do +/!1+ for 5 bytes. – streetster – 2017-08-10T14:12:26.383

1

Emojicode, 50 bytes

➡️➗✖➕1 2

Try it online!

betseg

Posted 2017-07-18T20:32:14.660

Reputation: 8 493

1

Recursiva, 3 bytes

sBa

Try it online!

Recursiva, 5 bytes

H*a;a

Try it online!

Recursive solution:

Recursiva, 12 bytes

=a0:0!+a#~a$

Try it online!

officialaimm

Posted 2017-07-18T20:32:14.660

Reputation: 2 739

1

Cubically, 19 bytes

R3U1F1$:1/1+7*7/0%6

How it works:

R3U1F1              Set the top face to 2
      $             Get the first input as a number
       :1/1+7       Set the notepad to the input + 1
             *7     Multiply the notepad by the input
               /0   Divide the notepad by 2
                 %6 Output the notepad as a number

TehPers

Posted 2017-07-18T20:32:14.660

Reputation: 899

1

Pyth, 11 9 bytes

VQ=+ZhN)Z

Explanation:

VQ       For N in range(0, Input)
=+ZhN)   Set Z to Z + 1 + N, suppress output and close function call
Z        Output Z

Try it online!

Stan Strum

Posted 2017-07-18T20:32:14.660

Reputation: 436

Beat you by 7 bytes – Tornado547 – 2017-12-11T16:38:16.317

@Tornado547 I know, but that answers been taken. This is just a unique way of doing it. 2 bytes: sS. – Stan Strum – 2017-12-11T16:39:39.250

1

,,,, 6 bytes

::×+2÷

Try it online!

Explanation:

::     Duplicates the input twice
  ×    Pops off top two values and muliples them
   +   Adds the two values together. (Thus far it's basically n*n+n)
    2÷ Divides by 2

Jchabin

Posted 2017-07-18T20:32:14.660

Reputation: 11

1

Alumin, 9 bytes

jqdhcpfaf

Try it online!

Explanation

jqdhcpfaf
j          numeric input
 q   p     whlie TOS > 0
  d        duplicate TOS
   hc      subtract 1
      f f  fold over...
       a   ... addition 

Conor O'Brien

Posted 2017-07-18T20:32:14.660

Reputation: 36 228

@Riker shoot lol done – Conor O'Brien – 2017-12-17T21:06:34.073

1

SNOBOL4 (CSNOBOL4), 62 40 38 bytes

 N =INPUT
 OUTPUT =N * (N + 1) / 2
END

Try it online!

Giuseppe

Posted 2017-07-18T20:32:14.660

Reputation: 21 077

1

Pyth - 2 Bytes

sS

Explanation:

sSQ Q added implicitly to resolve arity
s   sum of
 S  integers from one to
  Q input

Tornado547

Posted 2017-07-18T20:32:14.660

Reputation: 389

1

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

jrtapsell

Posted 2017-07-18T20:32:14.660

Reputation: 915

1

brainfuck, 14 bytes

,[[>+<<.>-]>-]

Try it online!

Takes input as character code, outputs as unary null bytes

Jo King

Posted 2017-07-18T20:32:14.660

Reputation: 38 234

1

Phooey, 10 bytes

&.@+1*/2$i

Try it online!

Explanation

&.@+1*/2$i
&.            write input to the tape
  @           push same input to the stack
   +1         increment tape value
     *        multiply tape value by popped stack value
      /2      divide it by 2
        $i    output as integer

Conor O'Brien

Posted 2017-07-18T20:32:14.660

Reputation: 36 228

1

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

Kevin Cruijssen

Posted 2017-07-18T20:32:14.660

Reputation: 67 575

1

Ahead, 6 bytes

IEK+O@

Try it online!

snail_

Posted 2017-07-18T20:32:14.660

Reputation: 1 982

1

@yBASIC, 10 bytes

?_*_+_>>!.

Input should be in _ (No input methods exist)

Explanation

N(N+1) can be rewritten as N*N+N. Dividing by 2 would then require parentheses, but a left shift can be used instead. !. is the same as !0.0 (logical not of 0), which is 1.

12Me21

Posted 2017-07-18T20:32:14.660

Reputation: 6 110

1

MathGolf, 2 bytes

╒Σ

Try it online!

Pretty much exactly the sum (Σ) of the range from 1 to input ()

Jo King

Posted 2017-07-18T20:32:14.660

Reputation: 38 234

1

Keg, 2 bytes (SBCS)

Ï⅀

TIO

Keg, 5 bytes (SBCS)

Ï∑+).

Explanation:

Ï#    Range from input to 0. The 0 will not affect the summation.
 ∑+#  Apply all stack: add.
   )# We have to complete the braces if we want to output as an integer.
    .#Output as an integer

TIO

user85052

Posted 2017-07-18T20:32:14.660

Reputation:

That's available on the github interpreter and theoretically, it should work. – Lyxal – 2019-10-13T01:13:18.340

-1 byte using the -hr flag – Lyxal – 2019-12-06T20:43:13.823

1

Gol><>, 7 bytes

I:P*2,h

Courtesy of JoKing

Try it online!

8 bytes

I::*+2,h

Try it online!

KrystosTheOverlord

Posted 2017-07-18T20:32:14.660

Reputation: 681

1

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!

FlipTack

Posted 2017-07-18T20:32:14.660

Reputation: 13 242

1

Symbolic Python, 14 bytes

_*=-~_*_/(_+_)

Try it online!

This basically evaluates to \$ \frac{ n^2 (n-1)}{2n} = \frac{ n (n-1)}{2}\$, which is the usual form for triangular numbers.

Jo King

Posted 2017-07-18T20:32:14.660

Reputation: 38 234

1

Shakespeare Programming Language, 154 bytes

(Whitespace added for readability)

S.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]
Ajax:
Listen tothy.
You is the quotient betweenthe product ofyou the sum ofyou a cat a big cat.
Open heart

Try it online!

Simple, just does n(n+1)/2.

Hello Goodbye

Posted 2017-07-18T20:32:14.660

Reputation: 442

1

Charcoal, 5 bytes

IΣ…·N

Try it online!

Explanation:

 Σ        The sum of
  …·N     the inclusive range from 0 to input
I          converted to a string

I tried to make it with the formula \$\frac{x(x+1)}{2}\$ but it took more characters.

Pseudo Nym

Posted 2017-07-18T20:32:14.660

Reputation: 181

1

Clojure - 19 bytes

#(apply +(range %))

Boring answer is boring...

nihilazo

Posted 2017-07-18T20:32:14.660

Reputation: 477

1

C (gcc), 19 bytes

#define f(n)n*-~n/2

Try it online!

C (gcc), 15 bytes

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

-5 bytes thanks to ceilingcat!

Try it online!

S.S. Anne

Posted 2017-07-18T20:32:14.660

Reputation: 1 161

@ceilingcat Huh. How does that work? – S.S. Anne – 2020-01-10T12:26:52.253

@JL2210 It's abusing the way GCC compiles the code without optimizations. – NieDzejkob – 2020-01-11T14:37:48.250

0

Tcl, 36 bytes

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

Try it online!

sergiol

Posted 2017-07-18T20:32:14.660

Reputation: 3 055

0

Tcl, 29 bytes

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

Try it online!

sergiol

Posted 2017-07-18T20:32:14.660

Reputation: 3 055

1If you've got two Tcl answers, you should probably put them in one answer. – numbermaniac – 2017-07-19T00:24:54.527

@numbermaniac I have three. – sergiol – 2017-07-19T00:29:39.660

6Ah. It's probably better to put them all in one answer, then. – numbermaniac – 2017-07-19T01:08:29.070

0

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

steenbergh

Posted 2017-07-18T20:32:14.660

Reputation: 7 772

0

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(^)

Blue

Posted 2017-07-18T20:32:14.660

Reputation: 26 661

0

Scala, 12 bytes

Gauss sum (12 bytes):

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

Naive version (14 bytes):

n=>1.to(n).sum

Tamoghna Chowdhury

Posted 2017-07-18T20:32:14.660

Reputation: 373

0

Clojure, 28 bytes

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

Joshua

Posted 2017-07-18T20:32:14.660

Reputation: 231

0

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

Dylan Meeus

Posted 2017-07-18T20:32:14.660

Reputation: 220

1(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. – TheLethalCoder – 2017-07-19T12:34:01.930

Side note: Use four spaces to format the code not back ticks. – TheLethalCoder – 2017-07-19T12:34:38.090

@TheLethalCoder thanks! I just found another Java answer to this thread which indeed does it a great deal shorter and does not print ^^ – Dylan Meeus – 2017-07-19T12:34:50.977

0

Clojure, 16 bytes

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

MattPutnam

Posted 2017-07-18T20:32:14.660

Reputation: 521

0

Groovy, 11 bytes

{it*++it/2}

Try it online!


The input is not modified by rules of Groovy clsures.

Magic Octopus Urn

Posted 2017-07-18T20:32:14.660

Reputation: 19 422

0

PHP, 35 34 32 25 bytes

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

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

ricdesi

Posted 2017-07-18T20:32:14.660

Reputation: 499

Save 6 bytes with $argn and -F – Titus – 2017-07-26T11:34:35.020

0

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!

Steadybox

Posted 2017-07-18T20:32:14.660

Reputation: 15 798

0

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

Clashsoft

Posted 2017-07-18T20:32:14.660

Reputation: 835

0

Swift 3, 60 Bytes

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

Try it online!

Mic1780

Posted 2017-07-18T20:32:14.660

Reputation: 121

0

Math++, 13 bytes

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

SuperJedi224

Posted 2017-07-18T20:32:14.660

Reputation: 11 342

0

Matlab/Octave, 12 bytes

@(n)sum(1:n)

Batman

Posted 2017-07-18T20:32:14.660

Reputation: 111

0

Perl 5, 11 bytes

10 bytes of code + 1 for -p

$_*=$_++/2

Try it online!

Xcali

Posted 2017-07-18T20:32:14.660

Reputation: 7 671

0

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

MD XF

Posted 2017-07-18T20:32:14.660

Reputation: 11 605

0

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

caird coinheringaahing

Posted 2017-07-18T20:32:14.660

Reputation: 13 702

Wow, someone other than me used Pushy! Quick correction: R generates from 1 to n, not 0 to n. – FlipTack – 2017-10-24T18:57:15.793

@FlipTack ah, thanks! The docs are a little confusing with X and R – caird coinheringaahing – 2017-10-24T18:58:56.167

Also, summing does not remove the items it is summing, so the stack finishes as [1,2,3,4,5,15] – FlipTack – 2017-11-21T07:32:38.767

0

Python 3, 35 bytes

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

bacchusbeale

Posted 2017-07-18T20:32:14.660

Reputation: 1 235

You can save 2 bytes by removing the 1, in the range argument. Try it online!

– caird coinheringaahing – 2017-11-02T07:57:50.173

0

C (gcc) 16 bytes

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

Try it online

PrincePolka

Posted 2017-07-18T20:32:14.660

Reputation: 653

Would it be possible to use n*=...? – Zacharý – 2017-12-27T12:48:49.643

@Zacharý that gives the wrong output for some input – PrincePolka – 2017-12-27T15:45:03.377

Whoops, forgot about order of operation – Zacharý – 2017-12-27T17:07:30.357

0

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!

FantaC

Posted 2017-07-18T20:32:14.660

Reputation: 1 425

0

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

KSmarts

Posted 2017-07-18T20:32:14.660

Reputation: 1 830

0

Windows batch, 57 21 bytes

Inspired by J42161217

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

stevefestl

Posted 2017-07-18T20:32:14.660

Reputation: 539

0

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

ბიმო

Posted 2017-07-18T20:32:14.660

Reputation: 15 345

0

Broccoli, 35, 33 bytes

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

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

(t 10)

James

Posted 2017-07-18T20:32:14.660

Reputation: 54 537

Surely n*(n+1)/2 should be shorter, even in this ridiculous language – Mego – 2018-01-12T05:25:45.663

@Mego Surprisingly, not by very much. And it outputs it as a float, not an int. I hope that's OK. – James – 2018-01-12T05:37:13.233

2I don't see why outputting as a float wouldn't be valid. There's a JS answer already. – Mego – 2018-01-12T05:38:16.663

(fn t($n)(/(* $n(+ 1 $n))2)) works too – ASCII-only – 2018-03-16T00:38:23.337

0

Pyt, 2 bytes

řƩ

Try it online!

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

golfed by mudkip

FantaC

Posted 2017-07-18T20:32:14.660

Reputation: 1 425

0

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!

Οurous

Posted 2017-07-18T20:32:14.660

Reputation: 7 916

0

Aheui (esotope), 33 bytes

방빠받반타다따반나망해

Try it online!

cobaltp

Posted 2017-07-18T20:32:14.660

Reputation: 401

0

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}

Conor O'Brien

Posted 2017-07-18T20:32:14.660

Reputation: 36 228

0

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.

Conor O'Brien

Posted 2017-07-18T20:32:14.660

Reputation: 36 228

0

Tir, 4 bytes

{∟+}

Try it online!

Explanation

{∟+}    a block
 ∟      range from 1 to the input
  +     sum that range

Conor O'Brien

Posted 2017-07-18T20:32:14.660

Reputation: 36 228

0

Fynyl, 5 bytes

{rf+}

Try it online!

Explanation

{rf+}    block
 r       range from 1 to input
  f+     fold addition (sum)

Conor O'Brien

Posted 2017-07-18T20:32:14.660

Reputation: 36 228

0

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             []

Conor O'Brien

Posted 2017-07-18T20:32:14.660

Reputation: 36 228

0

;#+, 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

Conor O'Brien

Posted 2017-07-18T20:32:14.660

Reputation: 36 228

0

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;}

Conor O'Brien

Posted 2017-07-18T20:32:14.660

Reputation: 36 228

0

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;}

Conor O'Brien

Posted 2017-07-18T20:32:14.660

Reputation: 36 228

0

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.

Draco18s no longer trusts SE

Posted 2017-07-18T20:32:14.660

Reputation: 3 053

0

W, 2 bytes

+R

Explanation

   % Implicit range from 1 .. input
+R % Reduce the array via addition

user85052

Posted 2017-07-18T20:32:14.660

Reputation:

0

Rust, 12 bytes

|n|n*(n+1)/2

Try it online!

Anonymous function.

NieDzejkob

Posted 2017-07-18T20:32:14.660

Reputation: 4 630

0

Z80Golf, 11 bytes

00000000: cd03 8047 af80 0520 fcff 76              ...G... ..v

Try it online!

I/O as byte values, takes a byte, outputs a byte. Assembly:

    call $8003
    ld b, a
    xor a
loop:
    add a, b
    dec b
    jr nz, loop
    rst $38
    halt

Z80Golf, 13 bytes

00000000: cd03 805f 193d 20fb 7dff 7cff 76         ..._.= .}.|.v

Try it online!

I/O as byte values, takes a byte, outputs two bytes little endian. Assembly:

    call $8003
loop:
    ld e, a 
    add hl, de
    dec a
    jr nz, loop
    ld a, l
    rst $38
    ld a, h
    rst $38
    halt

Z80Golf, 54 bytes

00000000: cd03 8038 0ed6 3029 e5d1 2929 195f 1600  ...8..0)..))._..
00000010: 1918 ede5 d11b 197b b220 facd 1f00 7611  .......{. ....v.
00000020: 0000 01f6 ff09 3003 1318 faeb d57d b4c4  ......0......}..
00000030: 1f00 d17b c63a                           ...{.:

Try it online!

Proper, decimal I/O. Uses a recursive output routine, with a particularly clever 0-byte tailcall:

get_input:
    call $8003
    jr c, got_input
    sub a, '0'
    add hl, hl
    push hl
    pop de
    add hl, hl
    add hl, hl
    add hl, de
    ld e, a
    ld d, 0
    add hl, de
    jr get_input

got_input:
    push hl
    pop de
loop:
    dec de
    add hl, de
    ld a, e
    or a, d
    jr nz, loop

    call output
    halt

; Input:
; HL = number to print
output:
    ld de, 0 ; quotient
    ld bc, -10
div_loop:
    add hl, bc
    jr nc, neg
    inc de
    jr div_loop
neg:
    ex de, hl
    ; now: hl = quotient, de = remainder - 10
    push de
    ld a, l
    or h
    call nz, output
    pop de
    ld a, e
    add '0' + 10
    ; fallthrough to $8000 where the output hook is

Everything assembled with WLA-DX. The -b flag was passed to wlalink, and the following memory map was used:

.ROMBANKMAP
    BANKSTOTAL 1
    BANKSIZE $10000
    BANKS 1
.ENDRO

.MEMORYMAP
    DEFAULTSLOT 0
    SLOTSIZE $10000
    SLOT 0 $0000
.ENDME

NieDzejkob

Posted 2017-07-18T20:32:14.660

Reputation: 4 630

-3

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

Yuval Meshorer

Posted 2017-07-18T20:32:14.660

Reputation: 33

4

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

– caird coinheringaahing – 2017-12-03T19:27:43.743

This would have to be lambda x:sum(range(n))+n for the rules. – MilkyWay90 – 2019-04-01T23:04:31.350