g | x | w | all
Bytes Lang Time Link
019How dare you fuck the brain241214T194959ZGleb
034SAKO250318T121208ZAcrimori
008awk221219T115802ZRARE Kpo
002Vyxal 3250221T154326ZThemooni
088Bespoke250216T105722ZJosiah W
003Jalapeño250205T042448ZATaco
012CASIO BASIC CASIO fx9750giii250126T222052Zmadeforl
nan250125T134101ZRARE Kpo
016BrainFlak170718T204120ZDJMcMayh
012Nibbles221219T125045ZDominic
017WendyScript170718T223156ZFelix Gu
009ARBLE230323T212838ZATaco
012AArch64 machine code230623T153853Zlandfill
031Scratch231127T120227ZRhaixer
028Fortran GFortran230323T165659Zroblogic
009bc231127T050216Zroblogic
009Trilangle230214T182531ZBbrk24
015Uiua231003T104537ZJeremy M
008ARM Thumb machine code231004T063210Zlandfill
028Swift230713T212723ZmacOSist
nanPiet + asciipiet220415T130046ZBubbler
029Go191218T225901ZFlipTack
003Ly230701T034920Zcnamejj
nan230616T185802ZDadsdy
000Vyxal Rs230623T190943ZThe Empt
011Desmoslang Assembly230530T040459ZDadsdy
001Thunno 2 S230528T142425ZThe Thon
022PowerShell230323T194010ZJames Fl
011Alice230324T005419ZJulian
017Binaryencoded Golfical230323T224913ZSuperJed
008TacO230323T211552ZATaco
012Arturo230323T200102Zchunes
570PIC16F88x Machine Code230323T041921ZBbrk24
719NASM 32 bits230214T174908ZIté
017F# .NET Core230201T011728Zdtanku
019Erlang230131T235904ZYuri Gin
014shell230129T205517Zgildux
055HP UserRPL230129T222300Zgildux
002Thunno +230129T170021ZThe Thon
001Japt mx221219T120226ZShaggy
002flax220421T063212Zzoomlogo
019Python 3220423T045150ZRhaixer
018Prolog SWI220902T134725ZJo King
1136Mornington Crescent220803T033927ZCloudy7
011Knight220801T233444ZnaffetS
001Chocolate220725T201215ZnaffetS
010BitCycle u220723T035440ZDLosc
002Regex 🐇 Perl / Raku / PCRE220722T170047ZDeadcode
013Retina 0.8.2170718T211835ZNeil
nanFig220722T212149ZSeggan
001Vyxal s210420T060328Zwasif
013Desmos220626T030939ZAiden Ch
000Vyxal Rs220603T025708ZnaffetS
007Juby220603T025512ZnaffetS
026MSWLogo220603T024650Zbadatgol
024Ruby220425T141422Zoeuf
012Factor + math.unicode220423T135059Zchunes
011Knight210611T204239ZEasyasPi
030tinylisp220209T135152ZRazetime
009Fourier220209T134141Zsinvec
018APOL211211T155106ZGinger
026Python 3211210T200505ZAlan Bag
008<>^v210613T020054Zastroide
008MAWP200928T083936ZDion
014Hexagony210610T052143ZJo King
012JavaScript Node.js170719T113224ZMadPhysi
287MMIX210421T013046ZNoLonger
144MashedPotatoes210420T084633Zcnamejj
016Hexagony210420T040515ZUndersla
012Branch210419T213122Zhyperneu
010Duocentehexaquinquagesimal210419T211841ZMakonede
003Bound201014T213757ZHoofedEa
003Arn200929T165920ZZippyMag
039Rockstar200928T101850ZShaggy
008Labyrinth200928T005451ZBubbler
011Z80Golf200111T143700ZMaya
012Rust200110T230609ZMaya
019C gcc200109T164106ZS.S. Ann
019Clojure200102T223526Zsoweli N
010C# Visual C# Interactive Compiler191219T133151ZJirka Pi
002W191220T101952Zuser8505
002Keg191012T154044Zuser8505
056Spice191219T224327ZSlord6
005Charcoal191219T211434ZPseudo N
154Shakespeare Programming Language191219T200527ZHello Go
014Symbolic Python191218T232836ZJo King
007Gol><>191016T014859ZKrystosT
008Runic Enchantments191015T135219ZDraco18s
002MathGolf190505T081159ZJo King
4429shortC170719T114039Zuser5882
010@yBASIC181230T180729Z12Me21
006Ahead181210T075039Zsnail_
071Whitespace181207T083012ZKevin Cr
010Phooey181207T045743ZConor O&
028DScript181207T045007ZConor O&
028D181207T044646ZConor O&
019#+181207T044227ZConor O&
006Somme181207T043536ZConor O&
005Fynyl181207T043203ZConor O&
004Tir181207T042733ZConor O&
008Attache181207T041459ZConor O&
013Tidy181207T041326ZConor O&
033Aheui esotope181207T003902Zcobaltp
001Japt x170718T210543ZOliver
040Alchemist181206T171018Zბიმო
026Clean180830T125142ZΟurous
014brainfuck180130T011414ZJo King
002Pyt180128T205608Zqqq
013Kotlin180128T213707Zjrtapsel
001Pyt171224T200716Zmudkip20
012Ruby170718T211019ZSnaddyvi
033Broccoli180112T052431ZDJMcMayh
006TIBasic170726T132059ZTimtech
029Functoid180112T035351Zბიმო
021Windows batch180112T023439Zstevefes
687Taxi170719T172859ZEngineer
301ArnoldC171218T152421Zbearacud
009Alumin171211T131508ZConor O&
038SNOBOL4 CSNOBOL4171211T162348ZGiuseppe
164COBOL GNU171211T182110ZKSmarts
002Pyth 2 Bytes171211T163605ZTornado5
009Aceto171211T160322Zqqq
003Recursiva170806T165525Z0xffcour
009Mathematica170718T223544ZZaMoC
016C gcc171203T223853ZPrincePo
016Python 2170719T164922ZRohit-Pa
016Symbolic Python171024T184757ZFlipTack
002Implicit170907T030626ZMD XF
035Python 3171102T070433Zbacchusb
310ArnoldC170909T041528Zfxwang
003Pushy171024T184615Zcaird co
009Add++170718T210851Zcaird co
005Check170718T220826ZEsolangi
013Haskell170718T204135Zბიმო
006170911T031336ZJchabin
009Pyth170824T072609ZStan Str
024brainfuck170908T140402ZJerry
013Math++170721T201433ZSuperJed
004MY170719T125058ZAdalynn
019Cubically170809T200957ZTehPers
001Braingolf170718T212922ZMayube
4615Vim170720T193819Zბიმო
0404170718T232302ZUriel
013Röda170806T162705Zfergusq
011Perl 5170801T020430ZXcali
006TIBASIC170721T173840Zuser1812
050Emojicode170730T120212Zbetseg
004J170718T232453Zcole
008Kona170727T121653Zkitcar20
461ArnoldC170726T125718ZV. Court
013Bash170726T113236Zuser4180
022C170718T223017Zuser2301
008x86_64 machine language Linux170718T231958Zceilingc
012Matlab/Octave170723T181559ZBatman
0128th170718T205747ZChaos Ma
007x8664 Machine Code170719T072305ZCody Gra
007Ly170718T230101ZLyricLy
017Forth170721T204222Zmbomb007
060Swift 3170721T201322ZMic1780
019Bash170719T004320ZIvan Bot
010Java170721T073758ZDavid Co
012Dyvil170720T185219ZClashsof
010Cubix170720T143446ZLuke
019Octave170718T210923ZLuis Men
010Triangular170720T002836ZMD XF
058Fortran 95170720T000512ZSteadybo
003APL170718T212608ZUriel
006170718T204722Ztotallyh
013R170718T214849ZForgotte
025PHP170719T182216Zricdesi
014Excel VBA170719T165356ZTaylor R
016Clojure170718T214524ZUriel
026Common Lisp170719T112927ZMadPhysi
012Excel170719T054347ZScott
002Gaia170719T151833ZBusiness
011Groovy170719T150343ZMagic Oc
016Clojure170719T145005ZMattPutn
009Befunge170719T144553ZVincent
015MUMPS170719T130231ZJoã
037Java 8170719T123239ZDylan Me
010Java OpenJDK 8170719T123512ZXanderha
009Carrot170719T121811ZTheLetha
047C170719T112311ZAgent_Me
002Jelly170718T204444Ztotallyh
028Clojure170719T112151ZJoshua
012Scala170719T095511ZTamoghna
019PHP170719T065407ZTitus
002Pyke170719T091640ZBlue
002Neim170719T001855ZLiefdeWe
032Lean Mean Bean Machine170718T233422ZMayube
00205AB1E170718T204240Zspace ju
015><>170719T065941Zsteenber
007Pip170719T073200Zsteenber
010QBIC170719T071355Zsteenber
006GolfScript170719T064143ZErik the
022Commentator170719T065721ZErik the
002Brachylog170719T062727ZFatalize
080C++ template metaprogramming170719T051015ZKeyu Gan
032Element170719T035959ZaAaa aAa
016Terrapin Logo170719T032748Zadrian
007dc170719T024407ZMax Mikh
nanPiet170718T215451Zბიმო
nan170719T024235ZBrad Gil
002cQuents170718T212013ZStephen
012Factor170719T012606Zcat
024Brainfuck170719T010841ZATaco
027Positron170719T003036Ztotallyh
009Casio Basic170718T235808Znumberma
029Tcl170718T235831Zsergiol
027Tcl170718T235600Zsergiol
022Starry170718T211532ZLuis Men
036Tcl170718T233905Zsergiol
002MATL170718T230052ZAlexRace
022AutoHotkey170718T214723ZMayube
009Mathematica170718T223154Znumberma
010Java OpenJDK 8170718T223059ZOlivier
010Julia170718T215632ZUriel
013Swift170718T215024ZMr. Xcod
001Husk170718T213146ZLeo
7310><>170718T211710ZEmigna
032BLua170718T210220Zuser7236
006CJam170718T210528ZLuis Men
010C# .NET Core170718T210043ZCharlie
018PowerShell170718T204346ZAdmBorkB
002Ohm170718T205139Ztotallyh
010JavaScript ES6170718T204510ZArnauld
016Python 2170718T204019Ztotallyh
002Pyth170718T204327ZJim
003Oasis170718T204225ZLeaky Nu

How dare you fuck the brain, 23 21 19 bytes

;=^|↑vv↓v+^^D=^)vvv

Stumbled across this question when i was trying to find the infinite loop MAWP entry

Try it online

SAKO, 34 bytes

PODPROGRAM:S(N)
S()=N×(N+1)/2
WROC
  1. Read the input to N.
  2. Sum and return the result.

awk 8 bytes

This variant just sums up 1st column of sequential integers

jot 14 | awk '$2=_+=$1' 

1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55
11 66
12 78
13 91
14 105

or

awk 8 bytes

This variant sum NR (aka line number).

jot -b '-' 14 | awk '$1=_+=NR'
1
3
6
10
15
21
28
36
45
55
66
78
91
105

This other variant that I didn't write, awk '$_*=$++_++/(_+_--)', is actually horrific, because (1) it's not portable across all awks, may return inaccurate results in large operands, even with gmp, since first divides before multiplying.

A much better version of that same idea, and even lower byte count of just 12, is

jot 14 | awk '$1=$_*++$_/2'

Vyxal 3, 2 bytes

ɾ∑
ɾ∑­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌­
ɾ   # ‎⁡range 1 inclusive
 ∑  # ‎⁢sum
💎

Created with the help of Luminespire. Vyxal It Online!

Bespoke, 88 bytes

could I do some addition?clearly
although preferred just to multiply
triangular number N

Calculates the \$n\$th triangular number.

Jalapeño, 3 bytes

‥1Σ

Explained

‥1Σ
‥1  # All integers (implicit input) to 1 inclusive
  Σ # Sum

Hex-Dump of Bytecode

       0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
0000: 2e 31 e9                                        

Try it Online!

CASIO BASIC (CASIO fx-9750giii), 12 bytes

?→N
.5N(N+1

or...

?→N
Σ(K,K,1,N

awk

function __(_) { return _++*_*_/(_+_) }

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

Or if this is easier to understand, here is a snippet of python which explains the general concept of this answer:

l = [int(input())] # implicit
accum = 0 # implicit

while l[-1] != 0:
    accum2 = 0 # implicit

    accum2 += l.pop() - 1
    l.append(accum2)
    accum2 += 1

    accum += accum2 # implicit

accum += l.pop() # remember that l = [0] right now

print(accum) # implicit

Nibbles, 1 byte (2 nibbles)

+,

No builtin for sum-over-list or flags for summation or range, but Nibbles still seems pretty competitive here...

+       # sum of list:
 ,      # range from 1..
        # (implicit) input

Attempt This Online!

WendyScript, 17 bytes

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

f(100) // => 5050

Try it online!

ARBLE, 15 9 bytes

n/2*(n+1)

Uninteresting answer, but more(?) interesting than sum(range(1,n))

Try it online!

AArch64 machine code, 12 bytes

0:  9b000000  madd  x0, x0, x0, x0
4:  d341fc00  lsr   x0, x0, #1
8:  d65f03c0  ret

Equivalent to:

uint64_t f(uint64_t n) {
  n = (n * n) + n;
  n = n >> 1;
  return n;
}

To test it, compile and run this C code with a GCC compatible compiler on AArch64 hardware via a Linux distro, Termux, Windows ARM64, etc.

#include <inttypes.h>
#include <stdio.h>

static uint64_t (*const f)(uint32_t) = (const uint32_t[]) {
  0x9b000000, // madd x0, x0, x0, x0
  0xd341fc00, // lsr  x0, x0, #1
  0xd65f03c0, // ret
};

int main(void) {
  uint32_t n = 5;
  scanf("%" SCNu32, &n);
  printf("%" PRIu64 "\n", f(n));
}

Note that I limited it to 32-bit inputs in the test code, because it overflows on the multiply-add when n >= (1 << 32).

It should work even in big-endian mode :)

Scratch, 31 bytes

Try it here

define(n
say(((n)*((n)+(1)))/(2

enter image description here

Fortran (GFortran), 35 28 bytes

Try it online!

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

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

read*,n;print*,sum([(j,j=1,n)]);end

bc, 9 bytes

n*(n+1)/2

Try it online!

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

Trilangle, 9 bytes

How appropriate that the triangular language is computing triangular numbers.

?2')2!*:@

Try it on the online interpreter!

Unwraps to this triangular grid:

   ?
  2 '
 ) 2 !
* : @ .

Instructions are executed in this order:

Effectively identical to this C program:

#include <stdio.h>

int main() {
  // ?
  int i; while(!scanf("%i", &i)) getchar();

  // 2)*
  i *= i + 1;

  // '2:
  i /= 2;

  // !
  printf("%d\n", i);

  // @
  return 0;
}

Uiua, 15 bytes

/+⇡+1parse&sc

Folds an array from 0 to the input number parsed as an integer.

Uiua Pad

ARM Thumb machine code, 8 bytes

0:  1c41  adds  r1, r0, #1  @  n + 1
2:  4348  muls  r0, r1      @  * n
4:  0840  lsrs  r0, r0, #1  @  / 2
6:  4770  bx    lr

Swift, 39 28 bytes

var s={(1...$0).reduce(0,+)}

Fairly self-explanatory.

Piet + ascii-piet, 16 bytes (4×4=16 codels)

tabR   Smm Amtqa

Try Piet online!

How it works

The code simply follows the border and then stops at the 3-cell L-shaped region. Basically uses the well-known formula, because setting up a loop here costs too many cells due to the necessary roll command.

Command    Stack
inN        [n]
dup 1 +    [n n+1]
* 2 /      [n*(n+1)/2]
outN       []

This layout saves two black cells over the following linear, more straightforward (pun intended) layout:

Piet + ascii-piet, 18 bytes (2×9=18 codels)

tabrsaqtM     a mm

Try Piet online!

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!

Ly, 3 bytes

R&+

Try it online!

A literal interpretation of the contest here...

R    - generate a range of numbers from 0 to "N" (from STDIN)
 &+  - sum the stack
     - print the stack as numeric values by default

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

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

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

Vyxal Rs, 0 bytes

Or 2 bytes depending on whether you count the flags here.


Try it Online!

Vyxal has useful flags.

Desmoslang Assembly, 11 Bytes

IS*.5(D+1OT

Thunno 2 S, 1 byte

R

Attempt This Online!

Thunno 2, 2 bytes

RS

Attempt This Online!

Pretty simple.

PowerShell, 22 bytes

1.."$args"-join'+'|iex

Try it online!

Alice, 11 bytes

/O
\I@/rd&+

Try it online!

/I\rd&+/O@   Full program flatened
/I\          Reads the input and push it on the stack
   r         Pops, Create a range from 0 to the input on the stack
    d        Pushes on the depth of the stack on the stack
             Flow control instructions
     &+      Pops sum all the numbers in the stack
       /O@   Prints and exit

Binary-encoded Golfical, 17 bytes

Hexdump of binary encoding:

00 90 01 15 0c 01 04 01 3c 0e 01 00
02 0a 01 3d 17

The encoded version can be converted to a runnable program image using the encoder utility included in the language's github repository, or run directly by using the -x flag

Original program image:

enter image description here

Magnified 45x with RGB colors labeled:

enter image description here

TacO, 8 bytes

@+%i
  i

A very simple solution. Iterates from 1 to the first argument, returning the index at each step, then sums the stack. Implicitly output.

@    ; Program Entry
+    ; Sum the result of
 %i  ; Loop from 1 to input
  i  ; Passed value of the loop

Try it online!

Arturo, 12 bytes

$=>[∑1..&]

Try it

PIC16F88x Machine Code, 5 words (70 bits)

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

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

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

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

In mpasm syntax:

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

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

NASM 32 bits, 719 bytes

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

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

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

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

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

F# (.NET Core), 12 17 bytes

let s x=(x+1)*x/2

Try it online!

Erlang 19 bytes

s(N) -> N*(N+1)/2.

shell, 17 14 bytes

First attempt was:

seq -s+ -t0 $1|bc

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

seq -s+0 $1|bc

HP UserRPL, 5.5 bytes

The source, pretty-formatted and commented:

«
  'X' @function@
  DUP @variable@
  1 @start@
  4 ROLL @end, ...is programm input@
  SEQ @create-list@
  ΣLIST @sum list items, equiv: « + » STREAM@
»

When saved in the calculator, @comments@ and extra spaces are lost.
The source you'll retrieve on your computer, using ASCII should look like

\<< 'X' DUP 1 4 ROLL SEQ \SigmaLIST \>>

In calculator, programs are saved with some kind of tokenisation where DUP and ROLL aren't 3 bytes but only half each.

Thunno +, 2 bytes

(actually \$ 2 \log_{256}(96) \approx \$ 1.65 bytes but that doesn't show up on the leaderboard)

RS

Attempt This Online!

Thunno, \$ 4 \log_{256}(96) \approx \$ 3.29 bytes

R1+S

Attempt This Online!

or

1+RS

Attempt This Online!

Explanations

RS  # Implicit input
    # The + flag pushes input+1
R   # Push range(0, input+1)
 S  # Sum this list
    # Implicit output
R1+S  # Implicit input
R     # Push range(0, input)
 1+   # Add one to each
   S  # Sum this list
      # Implicit output
1+RS  # Implicit input
1+    # Add one to the input
  R   # Push range(0, input+1)
   S  # Sum this list
      # Implicit output

Japt -mx, 1 byte

Ä

Try it

Ä     :Implicit map of each U in the range [0,input)
Ä     :Add 1
      :Implicit output of sum of resulting array

flax, 2 bytes

Σκ

Try It Online!

Explanation

Σκ
Σ     ⍝ sum of
 κ    ⍝ numbers from range 1...n

Python 3, 32 19 bytes

lambda z:z*(z+1)//2

-13 bytes because lambdas are small
-6 bytes due to a rereading.
-2 bytes thanks to @oeuf

Prolog (SWI), 18 bytes

N+R:-R is\N* -N/2.

Try it online!

Simple application of the formula

Mornington Crescent, 1136 bytes

I was surprised not to find an answer here already -- I thought we MC programmers had scoured the simpler challenges pretty clean.

Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Parsons Green
Take District Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Aldgate
Take Circle Line to Aldgate
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Aldgate
Take Circle Line to Hammersmith
Take Circle Line to Aldgate
Take Circle Line to Aldgate
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Aldgate
Take Circle Line to Aldgate
Take Circle Line to Victoria
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Victoria
Take District Line to Turnham Green
Take District Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take District Line to Upminster
Take District Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent

Try it online!

Summary of the program:

1. Parse integer from string using Parsons Green and store in Bank
(as far as I know, MC only supports string input)
2. Find bitwise negation of integer using Notting Hill Gate
3. Multiply integer by its bitwise negation using Chalfont & Latimer and store in Victoria
4. Calculate 1 by dividing the input integer by itself using Cannon Street
5. Retrieve stored value from Victoria and bitwise shift right by 1 using Turnham Green
6. Find bitwise negation of result using Notting Hill Gate
7. Add 1 to result using Upminster
8. Output the result via Mornington Crescent

Knight, 11 bytes

O/*+1=xPx 2

Try it online!

Chocolate, 1 byte

Try it online!

BitCycle -u, 11 10 bytes

-1 byte thanks to Jo King

 ~\~!
?AB^

Try it here!

Explanation

In BitCycle, numbers are represented in unary (with the -u flag allowing I/O to be given in decimal form for convenience). Thus, all we need is this algorithm:

Outputting unary numbers consecutively has the effect of adding them, thus giving n + (n-1) + ... + 1.

The number (as a string of 1 bits) comes in at the source ? and goes into the collector A, which then dumps it into the collector B. When the bits exit B, they are directed north into the dupneg ~, where a copy turns right (east) and a negated copy turns left (west). The original copy goes into the sink ! to be output. From the negated copy, one bit is sent north by the splitter \ and discarded. The rest get negated again by a second dupneg; the doubly negated bits go south into the A collector to begin the loop again, while the other copies go north off the playfield and are discarded. Once no bits are left, the program halts and outputs the sink's contents.

Regex 🐇 (Perl / Raku / PCRE), 2 bytes

x+

Takes its input in unary, as a string of x characters whose length represents the number. Returns its output as the number of ways the regex can match.

Try it online! - Perl v5.28.2 / Attempt This Online! - Perl v5.36+
Try it online! - Raku
Try it online! - PCRE1
Try it online! - PCRE2 v10.33 / Attempt This Online! - PCRE2 v10.40+

Although Perl, Raku, and PCRE2 are the only regex engines currently capable of counting the number of possible matches without their source code being patched, this solution itself obviously only uses the most basic regex functionality, universal to all regex engines.

x+ will match every possible non-empty substring exactly once. So for example with the input 5, it is converted to unary as xxxxx, and then the list of possible matches is the following set of substrings:

xxxxx, xxxx, xxx, xx, x
xxxx, xxx, xx, x
xxx, xx, x
xx, x
x

As such, counting these is equivalent to calculating the sum of all integers from \$1\$ to \$n\$ (a.k.a. the \$n\$th triangular number).

This can be extended in many interesting ways, for example raising numbers to a constant power.

Retina 1.0, 9 bytes

.+
*
w`.+

Input and output are both in decimal.

Try it online!

Explanation:

.+
*

Convert the input from decimal to unary, with _ as the repeating character.

w`.+

w enables full overlap mode, where all substrings are considered (this feature was introduced in Retina 1.0.0). .+ then matches the full set of non-empty substrings. Using .* instead, to match all substrings, would shift the sequence 1 forward: Try it online!

If the input were taken in unary, this solution would be 4 bytes: Try it online!

Retina is not capable of counting the number of ways a regex can match, only the number of unique substrings that match, so this method can't be directly extended any further than the triangular number sequence.

Retina 0.8.2, 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.

Fig, \$2\log_{256}(96)\approx\$ 1.646 bytes

Sa

See the README to see how to run this

Sa # Takes a number as input
S  # Sum
 a # Of the range [1, n]

Vyxal s, 1 byte

ɾ

Inclusive range of 1 to input, and s flag sums the stack.

Try it!

Desmos, 13 bytes

f(n)=.5nn+.5n

Very surprised that there wasn't a Desmos answer here yet.

Try It On Desmos!

Vyxal Rs, 0 bytes


Try it Online!

Lol

J-uby, 7 bytes

:+|:sum

Try it online!

MSWLogo, 26 bytes

to f :n
pr :n*(:n+1)/2
end

Proof of Correctness

Ruby, 24 bytes

n=gets.to_i;p n*(n+1)//2

Direct

Attempt This Online!

Ruby, 24 bytes

n=gets.to_i;p (1..n).sum

The same as previous, but using sum.

Attempt This Online!

Factor + math.unicode, 12 bytes

[ [1,b] Σ ]

Try it online!

Posting this here because the other Factor answer is incorrect.

Knight, 11 bytes

O/*+1=xPx 2

Try it online!

Ungolfed:

OUTPUT / (* (+1 = x PROMPT) x) 2

How the magic works:

This is using the fact that \$\sum_{n=1}^{x} n == \frac{x(x + 1)}{2}\$

  1. =xP First, we read a line from standard input and assign to x. Normally, we would do +0P to immediately coerce it to a Number, but I have better plans.
  2. +1=xP We add the result of the assignment to \$1\$. This coerces to Number for us, giving a result of Number.
  3. *+1=xPx We then multiply that by x. Since +1=xP is a Number, x will also be converted to a Number. Now, we have \$x(x + 1)\$.
  4. Last, divide by 2 and output.

tinylisp, 30 bytes

(d F(q((n)(i n(a n(F(s n 1)))0

Try it online!

Fourier, 9 bytes

I~_^*_/2o

Try it online!

APOL, 18 bytes

v(0);ⅎ(⧣ ∆(0 ∈));⁰

Python 3, 26 bytes

lambda n:sum(range(1,n+1))

Try it online!

Bewildered this isn't here yet.

<>^v, 8 bytes

,≈)*2?/;

Explanation

,≈)*2?/;

,         Read number from stdin
 ≈        Duplicate top of stack
  )       Increment top of stack
   *      Multiply top element of stack by second element of stack
    2     Push 2
     ?    Swap top two elements of stack
      /   Divide top element of stack by second element of stack
       ;  Print top of stack

run online

MAWP, 8 bytes

@!1+*2$:

Try it!

Old solution that manually loops through integers:

MAWP, 13 bytes

`0@[!\+/1-]`:

Try it!

Hexagony, 14 bytes

?'+\.*:){=/\!2

Try it online! or Try it in a visual editor!

Expanded out, this is:

  ? ' +
 \ . * :
) { = / \
 ! 2 . .
  . . .

It took quite a bit of effort to get from a trivial 15 byte modification of Underslash's answer (using a char literal for 2), to get to 14 bytes. We save that one byte by managing to reuse all of '{= at the cost of an extra control flow instruction, as well as by terminating through an error of division by zero. There's still one no-op in the middle of this, so perhaps 13 is possible (but unlikely)?

Expanding it out by following the control flow, we find this:

?'+){=*'2{+*=2?*:!2)+*=2?*:

Removing all the extra stuff that are basically no-ops or are there to force a specific path of execution, we get:

?'+){=*'2{=:!=:
?                 Get the input
 '+               Duplicate it to an adjacent edge
   )              Increment it
    {=*           Multiply the original by the incremented one
       '2         Place 2 in an adjacent cell
         {=:      Divide the result by 2
            !     And print
             =:   Divide by zero

JavaScript (Node.js), 12 bytes

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

Try it online!

MMIX, 28 bytes (7 instructions)

(a function)

23FF0001 1A0000FF 3F000001 FEFF0003
3BFFFF3F C00000FF F8010000

Dissassembly:

    ADDU $255,$0,1      // tmp = n + 1
    MULU $0,$0,$255     // rH:n = n * tmp
    SRU  $0,$0,1        // n >>>= 1
    GET  $255,rH        // tmp = rH
    SLU  $255,$255,63   // tmp <<= 63
    OR   $0,$0,$255     // n |= tmp
    POP  1,0            // return(n)

I used the obvious straight-line version. This computes the result mod \$2^{64}\$.

MashedPotatoes, 144 bytes

synchronized
(0.0f){casestd::ignoreof{_->usestrictqw/nullptr/;}goto++i;(formatt"WHILE$ARGV<$[SETLOCAL*read-eval*WEND")procFS{`uniq-c`}{s/()//g}}

MashedPotatoes isn't available on TIO, so here's the Esolangs page for reference.

https://esolangs.org/wiki/MashedPotatoes

The annotated code below might not make sense without reading about the quirky language syntax first, but here goes...

synchronized
(0.0f) {

Sets the value of Label0 to 2 (the line number where the ( appears. Important for register rotation expression later.

case std::ignore of { _ -> use strict qw/nullptr/; }

Read an integer from STDIN into register ^A.

goto ++i;

Shift the registers, meaning ^A -> ^C -> ^E, to move the input to ^C.

(format t "

Loops while the contents of ^C are greater than 0.

WHILE $ARGV < $[ SETLOCAL *read-eval* WEND

Adds the value of ^C to register ^E.

")

End of loop, automatically decrements ^C.

proc FS {`uniq -c`} { s/()//g }

Prints the contents of ^E.

}

Just closing the synchronized statement to end the program cleanly

Hexagony, 16 bytes

?"&{2'<)}=*/@!:=

Try it online! Try it online differently!

Branch, 12 bytes

^\n}^*^\2^:#

Try it on the online Branch interpreter!

Uses n * (n - 1) / 2

A solution that actually properly produces all the numbers and sums them:

Branch, 15 bytes

[/;{]^[\;^+^]/#

Try it on the online Branch interpreter!

And if you replace the # with ` (shorthand for `P when at the end of a program) you can see that it places the cumulative sums along the main left branch.

Duocentehexaquinquagesimal, 10 bytes

1ËвáýŸÚ¦˜Í

Try it online! I/O as characters.

Bound, 3 bytes

i&n

Explanation:

i # Gets input and puts it onto the stack if its an int
& # Pops the top element, and puts the range of 1 to n on the stack
n # Sums all ints in the stack

Try it online!

Arn, 3 bytes

+\~

Try it!

+\ -> Fold with sum ~ -> One-range to _ -> Input; implied

Rockstar, 39 bytes

listen to N
cast N
let N be*N+1
say N/2

Try it here (Code will need to be pasted in)

Labyrinth, 8 bytes

?:)*_2/!

Try it online!

A linear program which halts by error at the bounced-off / (triggering division by zero).

?:)*  Push input, dup, increment, multiply (giving n*(n+1))
_2/   Divide by 2
!     Pop and print, bounce off the dead end
/     The top is (implicit) 0 so it triggers division by zero error

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

Rust, 12 bytes

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

Try it online!

Anonymous function.

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!

Clojure - 19 bytes

#(apply +(range %))

Boring answer is boring...

C# (Visual C# Interactive Compiler), 29 22 10 bytes

n=>n*++n/2

Try it online!

W, 2 bytes

+R

Explanation

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

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

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

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.

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.

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.

Gol><>, 7 bytes

I:P*2,h

Courtesy of JoKing

Try it online!

8 bytes

I::*+2,h

Try it online!

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.

MathGolf, 2 bytes

╒Σ

Try it online!

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

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.

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

Ahead, 6 bytes

IEK+O@

Try it online!

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

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

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

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

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

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

Fynyl, 5 bytes

{rf+}

Try it online!

Explanation

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

Tir, 4 bytes

{∟+}

Try it online!

Explanation

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

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.

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}

Aheui (esotope), 33 bytes

방빠받반타다따반나망해

Try it online!

Japt -x, 3 1 bytes

ò

Explanation:

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

Try it online!

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:

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

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!

brainfuck, 14 bytes

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

Try it online!

Takes input as character code, outputs as unary null bytes

Pyt, 2 bytes

řƩ

Try it online!

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

golfed by mudkip

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

Pyt, 1 byte

Try it online!

Explanation:

               implicit input
 △             compute the nth triangle number

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!

Broccoli, 35, 33 bytes

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

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

(t 10)

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

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

Windows batch, 57 21 bytes

Inspired by J42161217

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

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

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!

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 

SNOBOL4 (CSNOBOL4), 62 40 38 bytes

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

Try it online!

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

Pyth - 2 Bytes

sS

Explanation:

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

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!

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!

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]

C (gcc) 16 bytes

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

Try it online

Python 2, 16 bytes

lambda n:-~n*n/2

Try it online!

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

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

Python 3, 35 bytes

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

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!

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

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)

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.

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!

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

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!

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 

Math++, 13 bytes

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

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)

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

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.

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

4, 40 bytes

3.70060101002000120300026040230503045054

Try it online!

Röda, 13 bytes

{seq 1,_|sum}

Try it online!

Perl 5, 11 bytes

10 bytes of code + 1 for -p

$_*=$_++/2

Try it online!

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

Emojicode, 50 bytes

🐖🔢➡️🚂🍇🍎➗✖🐕➕🐕1 2🍉

Try it online!

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

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

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!

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.

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

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.

Matlab/Octave, 12 bytes

@(n)sum(1:n)

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

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.

Ly, 26 7 bytes

n:1+*2/u

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

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.

Swift 3, 60 Bytes

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

Try it online!

Bash, 26, 19 bytes

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

Try it online!

19 bytes for the code, thanks to rexkogitans.

Java, 10 bytes

n->n*-~n/2

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

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

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

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.

Triangular, 10 bytes

$\:_%i/2*<

Ungolfed:

   $
  \ :
 _ % i
/ 2 * <

Try it online!

The code, without directionals, is read as $:i*2_%.

Idea thanks to caird, who asked me to post.

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!

APL, 3 bytes

+/⍳

Try it online!

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

,,,, 6 bytes

:1+×2÷

Explanation

:1+×2÷

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

If I implement range any time soon...

R, 13 bytes

sum(1:scan())

Saved 9 bytes thanks to Giuseppe and Max Lawnboy.

PHP, 35 34 32 25 bytes

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

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

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]

Clojure, 31 23 16 bytes

8 bytes saved thanks to @cliffroot

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

Try it online!

Common Lisp, 26 bytes

(lambda(n)(/(+(* n n)n)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.

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.

Groovy, 11 bytes

{it*++it/2}

Try it online!


The input is not modified by rules of Groovy clsures.

Clojure, 16 bytes

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

Befunge, 9 bytes

&:1+*2/.@

Try it online!

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.

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

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.

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

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

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

Clojure, 28 bytes

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

Scala, 12 bytes

Gauss sum (12 bytes):

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

Naive version (14 bytes):

n=>1.to(n).sum

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;

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

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

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.

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 

><>, 20 15 bytes

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

@notatree saved me a couple bytes!

Try it online!

Pip, 7 bytes

a*++a/2

Try it online!

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

GolfScript, 7 6 bytes

~.)2/*

Try it online!

Commentator, 22 bytes

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

Try it online!

Brachylog, 2 bytes

⟦+

Try it online!

Explanation

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

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

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

Terrapin Logo, 16 bytes

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

dc, 7 bytes

d1+*2/p

OR

d2^+2/p

OR

dd*+2/p

Try it online!

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

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)

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

Factor, 12 bytes

[ iota sum ]

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

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

Positron, 27 bytes

Positron is a new practical language by @HyperNeutrino.

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

Try it online!

Casio Basic, 9 bytes

(n+1)n/2

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

Tcl, 29 bytes

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

Try it online!

Tcl, 27 bytes

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

Try it online!

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

Tcl, 36 bytes

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

Try it online!

MATL, 2 bytes

:s

Try it online!

Not happy smiley.

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.

Mathematica, 9 bytes

#(#+1)/2&

or, at 11 bytes,

Tr@Range@#&

Java (OpenJDK 8), 10 bytes

n->n++*n/2

Try it online!

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!

Swift, 13 bytes

Anonymous function:

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

You can call it like this:

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

Try it online!

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.

><>, 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!

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

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

C# (.NET Core), 10 bytes

n=>n++*n/2

Try it online!

PowerShell, 22 18 bytes

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

Try it online!

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

Ohm, 2 bytes

Try it online!

Explanation

@Σ

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

JavaScript (ES6), 10 bytes

n=>n*++n/2

Example

let f =

n=>n*++n/2

console.log(f(5))

Python 2, 24 16 bytes

-8 bytes thanks to FryAmTheEggman.

lambda n:n*-~n/2

Try it online!

Pyth, 2 bytes

sS

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

Oasis, 3 bytes

n+0

Try it online!

How it works

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