| Bytes | Lang | Time | Link |
|---|---|---|---|
| 019 | How dare you fuck the brain | 241214T194959Z | Gleb |
| 034 | SAKO | 250318T121208Z | Acrimori |
| 008 | awk | 221219T115802Z | RARE Kpo |
| 002 | Vyxal 3 | 250221T154326Z | Themooni |
| 088 | Bespoke | 250216T105722Z | Josiah W |
| 003 | Jalapeño | 250205T042448Z | ATaco |
| 012 | CASIO BASIC CASIO fx9750giii | 250126T222052Z | madeforl |
| nan | 250125T134101Z | RARE Kpo | |
| 016 | BrainFlak | 170718T204120Z | DJMcMayh |
| 012 | Nibbles | 221219T125045Z | Dominic |
| 017 | WendyScript | 170718T223156Z | Felix Gu |
| 009 | ARBLE | 230323T212838Z | ATaco |
| 012 | AArch64 machine code | 230623T153853Z | landfill |
| 031 | Scratch | 231127T120227Z | Rhaixer |
| 028 | Fortran GFortran | 230323T165659Z | roblogic |
| 009 | bc | 231127T050216Z | roblogic |
| 009 | Trilangle | 230214T182531Z | Bbrk24 |
| 015 | Uiua | 231003T104537Z | Jeremy M |
| 008 | ARM Thumb machine code | 231004T063210Z | landfill |
| 028 | Swift | 230713T212723Z | macOSist |
| nan | Piet + asciipiet | 220415T130046Z | Bubbler |
| 029 | Go | 191218T225901Z | FlipTack |
| 003 | Ly | 230701T034920Z | cnamejj |
| nan | 230616T185802Z | Dadsdy | |
| 000 | Vyxal Rs | 230623T190943Z | The Empt |
| 011 | Desmoslang Assembly | 230530T040459Z | Dadsdy |
| 001 | Thunno 2 S | 230528T142425Z | The Thon |
| 022 | PowerShell | 230323T194010Z | James Fl |
| 011 | Alice | 230324T005419Z | Julian |
| 017 | Binaryencoded Golfical | 230323T224913Z | SuperJed |
| 008 | TacO | 230323T211552Z | ATaco |
| 012 | Arturo | 230323T200102Z | chunes |
| 570 | PIC16F88x Machine Code | 230323T041921Z | Bbrk24 |
| 719 | NASM 32 bits | 230214T174908Z | Ité |
| 017 | F# .NET Core | 230201T011728Z | dtanku |
| 019 | Erlang | 230131T235904Z | Yuri Gin |
| 014 | shell | 230129T205517Z | gildux |
| 055 | HP UserRPL | 230129T222300Z | gildux |
| 002 | Thunno + | 230129T170021Z | The Thon |
| 001 | Japt mx | 221219T120226Z | Shaggy |
| 002 | flax | 220421T063212Z | zoomlogo |
| 019 | Python 3 | 220423T045150Z | Rhaixer |
| 018 | Prolog SWI | 220902T134725Z | Jo King |
| 1136 | Mornington Crescent | 220803T033927Z | Cloudy7 |
| 011 | Knight | 220801T233444Z | naffetS |
| 001 | Chocolate | 220725T201215Z | naffetS |
| 010 | BitCycle u | 220723T035440Z | DLosc |
| 002 | Regex 🐇 Perl / Raku / PCRE | 220722T170047Z | Deadcode |
| 013 | Retina 0.8.2 | 170718T211835Z | Neil |
| nan | Fig | 220722T212149Z | Seggan |
| 001 | Vyxal s | 210420T060328Z | wasif |
| 013 | Desmos | 220626T030939Z | Aiden Ch |
| 000 | Vyxal Rs | 220603T025708Z | naffetS |
| 007 | Juby | 220603T025512Z | naffetS |
| 026 | MSWLogo | 220603T024650Z | badatgol |
| 024 | Ruby | 220425T141422Z | oeuf |
| 012 | Factor + math.unicode | 220423T135059Z | chunes |
| 011 | Knight | 210611T204239Z | EasyasPi |
| 030 | tinylisp | 220209T135152Z | Razetime |
| 009 | Fourier | 220209T134141Z | sinvec |
| 018 | APOL | 211211T155106Z | Ginger |
| 026 | Python 3 | 211210T200505Z | Alan Bag |
| 008 | <>^v | 210613T020054Z | astroide |
| 008 | MAWP | 200928T083936Z | Dion |
| 014 | Hexagony | 210610T052143Z | Jo King |
| 012 | JavaScript Node.js | 170719T113224Z | MadPhysi |
| 287 | MMIX | 210421T013046Z | NoLonger |
| 144 | MashedPotatoes | 210420T084633Z | cnamejj |
| 016 | Hexagony | 210420T040515Z | Undersla |
| 012 | Branch | 210419T213122Z | hyperneu |
| 010 | Duocentehexaquinquagesimal | 210419T211841Z | Makonede |
| 003 | Bound | 201014T213757Z | HoofedEa |
| 003 | Arn | 200929T165920Z | ZippyMag |
| 039 | Rockstar | 200928T101850Z | Shaggy |
| 008 | Labyrinth | 200928T005451Z | Bubbler |
| 011 | Z80Golf | 200111T143700Z | Maya |
| 012 | Rust | 200110T230609Z | Maya |
| 019 | C gcc | 200109T164106Z | S.S. Ann |
| 019 | Clojure | 200102T223526Z | soweli N |
| 010 | C# Visual C# Interactive Compiler | 191219T133151Z | Jirka Pi |
| 002 | W | 191220T101952Z | user8505 |
| 002 | Keg | 191012T154044Z | user8505 |
| 056 | Spice | 191219T224327Z | Slord6 |
| 005 | Charcoal | 191219T211434Z | Pseudo N |
| 154 | Shakespeare Programming Language | 191219T200527Z | Hello Go |
| 014 | Symbolic Python | 191218T232836Z | Jo King |
| 007 | Gol><> | 191016T014859Z | KrystosT |
| 008 | Runic Enchantments | 191015T135219Z | Draco18s |
| 002 | MathGolf | 190505T081159Z | Jo King |
| 4429 | shortC | 170719T114039Z | user5882 |
| 010 | @yBASIC | 181230T180729Z | 12Me21 |
| 006 | Ahead | 181210T075039Z | snail_ |
| 071 | Whitespace | 181207T083012Z | Kevin Cr |
| 010 | Phooey | 181207T045743Z | Conor O& |
| 028 | DScript | 181207T045007Z | Conor O& |
| 028 | D | 181207T044646Z | Conor O& |
| 019 | #+ | 181207T044227Z | Conor O& |
| 006 | Somme | 181207T043536Z | Conor O& |
| 005 | Fynyl | 181207T043203Z | Conor O& |
| 004 | Tir | 181207T042733Z | Conor O& |
| 008 | Attache | 181207T041459Z | Conor O& |
| 013 | Tidy | 181207T041326Z | Conor O& |
| 033 | Aheui esotope | 181207T003902Z | cobaltp |
| 001 | Japt x | 170718T210543Z | Oliver |
| 040 | Alchemist | 181206T171018Z | ბიმო |
| 026 | Clean | 180830T125142Z | Οurous |
| 014 | brainfuck | 180130T011414Z | Jo King |
| 002 | Pyt | 180128T205608Z | qqq |
| 013 | Kotlin | 180128T213707Z | jrtapsel |
| 001 | Pyt | 171224T200716Z | mudkip20 |
| 012 | Ruby | 170718T211019Z | Snaddyvi |
| 033 | Broccoli | 180112T052431Z | DJMcMayh |
| 006 | TIBasic | 170726T132059Z | Timtech |
| 029 | Functoid | 180112T035351Z | ბიმო |
| 021 | Windows batch | 180112T023439Z | stevefes |
| 687 | Taxi | 170719T172859Z | Engineer |
| 301 | ArnoldC | 171218T152421Z | bearacud |
| 009 | Alumin | 171211T131508Z | Conor O& |
| 038 | SNOBOL4 CSNOBOL4 | 171211T162348Z | Giuseppe |
| 164 | COBOL GNU | 171211T182110Z | KSmarts |
| 002 | Pyth 2 Bytes | 171211T163605Z | Tornado5 |
| 009 | Aceto | 171211T160322Z | qqq |
| 003 | Recursiva | 170806T165525Z | 0xffcour |
| 009 | Mathematica | 170718T223544Z | ZaMoC |
| 016 | C gcc | 171203T223853Z | PrincePo |
| 016 | Python 2 | 170719T164922Z | Rohit-Pa |
| 016 | Symbolic Python | 171024T184757Z | FlipTack |
| 002 | Implicit | 170907T030626Z | MD XF |
| 035 | Python 3 | 171102T070433Z | bacchusb |
| 310 | ArnoldC | 170909T041528Z | fxwang |
| 003 | Pushy | 171024T184615Z | caird co |
| 009 | Add++ | 170718T210851Z | caird co |
| 005 | Check | 170718T220826Z | Esolangi |
| 013 | Haskell | 170718T204135Z | ბიმო |
| 006 | 170911T031336Z | Jchabin | |
| 009 | Pyth | 170824T072609Z | Stan Str |
| 024 | brainfuck | 170908T140402Z | Jerry |
| 013 | Math++ | 170721T201433Z | SuperJed |
| 004 | MY | 170719T125058Z | Adalynn |
| 019 | Cubically | 170809T200957Z | TehPers |
| 001 | Braingolf | 170718T212922Z | Mayube |
| 4615 | Vim | 170720T193819Z | ბიმო |
| 040 | 4 | 170718T232302Z | Uriel |
| 013 | Röda | 170806T162705Z | fergusq |
| 011 | Perl 5 | 170801T020430Z | Xcali |
| 006 | TIBASIC | 170721T173840Z | user1812 |
| 050 | Emojicode | 170730T120212Z | betseg |
| 004 | J | 170718T232453Z | cole |
| 008 | Kona | 170727T121653Z | kitcar20 |
| 461 | ArnoldC | 170726T125718Z | V. Court |
| 013 | Bash | 170726T113236Z | user4180 |
| 022 | C | 170718T223017Z | user2301 |
| 008 | x86_64 machine language Linux | 170718T231958Z | ceilingc |
| 012 | Matlab/Octave | 170723T181559Z | Batman |
| 012 | 8th | 170718T205747Z | Chaos Ma |
| 007 | x8664 Machine Code | 170719T072305Z | Cody Gra |
| 007 | Ly | 170718T230101Z | LyricLy |
| 017 | Forth | 170721T204222Z | mbomb007 |
| 060 | Swift 3 | 170721T201322Z | Mic1780 |
| 019 | Bash | 170719T004320Z | Ivan Bot |
| 010 | Java | 170721T073758Z | David Co |
| 012 | Dyvil | 170720T185219Z | Clashsof |
| 010 | Cubix | 170720T143446Z | Luke |
| 019 | Octave | 170718T210923Z | Luis Men |
| 010 | Triangular | 170720T002836Z | MD XF |
| 058 | Fortran 95 | 170720T000512Z | Steadybo |
| 003 | APL | 170718T212608Z | Uriel |
| 006 | 170718T204722Z | totallyh | |
| 013 | R | 170718T214849Z | Forgotte |
| 025 | PHP | 170719T182216Z | ricdesi |
| 014 | Excel VBA | 170719T165356Z | Taylor R |
| 016 | Clojure | 170718T214524Z | Uriel |
| 026 | Common Lisp | 170719T112927Z | MadPhysi |
| 012 | Excel | 170719T054347Z | Scott |
| 002 | Gaia | 170719T151833Z | Business |
| 011 | Groovy | 170719T150343Z | Magic Oc |
| 016 | Clojure | 170719T145005Z | MattPutn |
| 009 | Befunge | 170719T144553Z | Vincent |
| 015 | MUMPS | 170719T130231Z | Joã |
| 037 | Java 8 | 170719T123239Z | Dylan Me |
| 010 | Java OpenJDK 8 | 170719T123512Z | Xanderha |
| 009 | Carrot | 170719T121811Z | TheLetha |
| 047 | C | 170719T112311Z | Agent_Me |
| 002 | Jelly | 170718T204444Z | totallyh |
| 028 | Clojure | 170719T112151Z | Joshua |
| 012 | Scala | 170719T095511Z | Tamoghna |
| 019 | PHP | 170719T065407Z | Titus |
| 002 | Pyke | 170719T091640Z | Blue |
| 002 | Neim | 170719T001855Z | LiefdeWe |
| 032 | Lean Mean Bean Machine | 170718T233422Z | Mayube |
| 002 | 05AB1E | 170718T204240Z | space ju |
| 015 | ><> | 170719T065941Z | steenber |
| 007 | Pip | 170719T073200Z | steenber |
| 010 | QBIC | 170719T071355Z | steenber |
| 006 | GolfScript | 170719T064143Z | Erik the |
| 022 | Commentator | 170719T065721Z | Erik the |
| 002 | Brachylog | 170719T062727Z | Fatalize |
| 080 | C++ template metaprogramming | 170719T051015Z | Keyu Gan |
| 032 | Element | 170719T035959Z | aAaa aAa |
| 016 | Terrapin Logo | 170719T032748Z | adrian |
| 007 | dc | 170719T024407Z | Max Mikh |
| nan | Piet | 170718T215451Z | ბიმო |
| nan | 170719T024235Z | Brad Gil | |
| 002 | cQuents | 170718T212013Z | Stephen |
| 012 | Factor | 170719T012606Z | cat |
| 024 | Brainfuck | 170719T010841Z | ATaco |
| 027 | Positron | 170719T003036Z | totallyh |
| 009 | Casio Basic | 170718T235808Z | numberma |
| 029 | Tcl | 170718T235831Z | sergiol |
| 027 | Tcl | 170718T235600Z | sergiol |
| 022 | Starry | 170718T211532Z | Luis Men |
| 036 | Tcl | 170718T233905Z | sergiol |
| 002 | MATL | 170718T230052Z | AlexRace |
| 022 | AutoHotkey | 170718T214723Z | Mayube |
| 009 | Mathematica | 170718T223154Z | numberma |
| 010 | Java OpenJDK 8 | 170718T223059Z | Olivier |
| 010 | Julia | 170718T215632Z | Uriel |
| 013 | Swift | 170718T215024Z | Mr. Xcod |
| 001 | Husk | 170718T213146Z | Leo |
| 7310 | ><> | 170718T211710Z | Emigna |
| 032 | BLua | 170718T210220Z | user7236 |
| 006 | CJam | 170718T210528Z | Luis Men |
| 010 | C# .NET Core | 170718T210043Z | Charlie |
| 018 | PowerShell | 170718T204346Z | AdmBorkB |
| 002 | Ohm | 170718T205139Z | totallyh |
| 010 | JavaScript ES6 | 170718T204510Z | Arnauld |
| 016 | Python 2 | 170718T204019Z | totallyh |
| 002 | Pyth | 170718T204327Z | Jim |
| 003 | Oasis | 170718T204225Z | Leaky 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
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
CASIO BASIC (CASIO fx-9750giii), 12 bytes
?→N
.5N(N+1
or...
?→N
Σ(K,K,1,N
awk
function __(_) { return _++*_*_/(_+_) }
Brain-Flak, 16 bytes
({({}[()])()}{})
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
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 :)
Fortran (GFortran), 35 28 bytes
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
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:
?: Read an integer from STDIN2: Duplicate the top of the stack): Increment the top of the stack*: Multiply the two values off the top of the stack'2: Push the number 2 to the stack:: Divide the two values off the top of the stack!: Print the top of the stack as a decimal number@: Terminate program.
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;
}
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
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
Go, 29 bytes
A function literal which uses the closed form, \$ \frac n2(n+1) \$.
func(n int)int{return-^n*n/2}
Ly, 3 bytes
R&+
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
Desmoslang Assembly, 11 Bytes
IS*.5(D+1OT
Alice, 11 bytes
/O
\I@/rd&+
/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:

Magnified 45x with RGB colors labeled:

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
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
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
Thunno, \$ 4 \log_{256}(96) \approx \$ 3.29 bytes
R1+S
or
1+RS
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
Ä
Ä :Implicit map of each U in the range [0,input)
Ä :Add 1
:Implicit output of sum of resulting array
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
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
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
BitCycle -u, 11 10 bytes
-1 byte thanks to Jo King
~\~!
?AB^
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:
- Input a number
- Loop while the number is nonzero:
- Output the current number
- Decrement the current number
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.
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]
Ruby, 24 bytes
n=gets.to_i;p n*(n+1)//2
Direct
Ruby, 24 bytes
n=gets.to_i;p (1..n).sum
The same as previous, but using sum.
Factor + math.unicode, 12 bytes
[ [1,b] Σ ]
Posting this here because the other Factor answer is incorrect.
Knight, 11 bytes
O/*+1=xPx 2
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}\$
=xPFirst, we read a line from standard input and assign tox. Normally, we would do+0Pto immediately coerce it to a Number, but I have better plans.+1=xPWe add the result of the assignment to \$1\$. This coerces to Number for us, giving a result of Number.*+1=xPxWe then multiply that byx. Since+1=xPis a Number,xwill also be converted to a Number. Now, we have \$x(x + 1)\$.- Last, divide by 2 and output.
APOL, 18 bytes
v(0);ⅎ(⧣ ∆(0 ∈));⁰
<>^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
MAWP, 8 bytes
@!1+*2$:
Old solution that manually loops through integers:
MAWP, 13 bytes
`0@[!\+/1-]`:
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
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
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.
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
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/!
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
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
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 ...{.:
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
C (gcc), 19 bytes
#define f(n)n*-~n/2
C (gcc), 15 bytes
f(n){n*=-~n/2;}
-5 bytes thanks to ceilingcat!
Clojure - 19 bytes
#(apply +(range %))
Boring answer is boring...
Keg, 2 bytes (SBCS)
Ï⅀
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
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
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
Simple, just does n(n+1)/2.
Symbolic Python, 14 bytes
_*=-~_*_/(_+_)
This basically evaluates to \$ \frac{ n^2 (n-1)}{2n} = \frac{ n (n-1)}{2}\$, which is the usual form for triangular numbers.
Runic Enchantments, 8 bytes
i:1+*2,@
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.
shortC, 44 29 bytes
Bn){K"%d",&n);R"%d",n*(n+1)/2
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.
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
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;}
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;}
Alternatively, 61 bytes: import std.range;N f(N)(N n){return std.range.iota(n).sum+n;}
;#+, 19 bytes
*;(~;~*;)-~(~+~;)+p
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.
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 []
Attache, 8 bytes
Sum@1&`:
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}
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}
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.
Pyt, 2 bytes
řƩ
implicit input ř returns [1, 2, 3, ... , top value] Ʃ sums top value implicit output
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
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
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[+))$.@
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.
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
Alumin, 9 bytes
jqdhcpfaf
Explanation
jqdhcpfaf
j numeric input
q p whlie TOS > 0
d duplicate TOS
hc subtract 1
f f fold over...
a ... addition
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.
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.
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
Recursiva, 3 bytes
sBa
Recursiva, 5 bytes
H*a;a
Recursive solution:
Recursiva, 12 bytes
=a0:0!+a#~a$
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]
Symbolic Python, 35 33 18 16 bytes
_=-~_*_/-~(_==_)
Uses the direct formula for triangle numbers, (n+1)(n/2):
_= # Set output to
-~_ # (n+1)
*_ # *n
/-~(_==_) # /2
Implicit, 2 bytes
¡Þ
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 :)
Pushy, 3 bytes
RS#
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+
ಠ_ಠ 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!
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]
Direct, 17 13 bytes
f n=n*(n+1)/2
Thanks @WheatWizard for -4 bytes!
Pointfree direct, 15 bytes
(*)=<<(/2).(+1)
Thanks @nimi for the idea!
Pointfree via sum, 16 bytes
sum.enumFromTo 1
Recursively, 22 18 bytes
f 0=0;f n=n+f(n-1)
Thanks @maple_shaft for the idea & @Laikoni for golfing it!
Standard fold, 19 bytes
f n=foldr(+)0[1..n]
,,,, 6 bytes
::×+2÷
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
brainfuck, 24 bytes
Input number in base255(ASCII), use bigger cells for larger numbers, outputs also in base255.
,[[>+>+<<-]>[-<+>]<-]>>.
,[ 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Σ↵
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
Vim, 4̶6̶ 25 17 16 15 keystrokes
Thanks @CowsQuack for -9 bytes!
YP<C-a>Jr*0C<C-r>=<C-r>"/2⏎
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
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
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.
Bash, 13 bytes
seq -s+ $1|bc
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) );
}
}
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.
Forth, 17 bytes
Defines a word (function) that returns n*(n+1)/2.
: f dup 1+ * 2/ ;
Full program with the same byte count:
key dup 1+ * 2/ .
Try it online - input is a single character, like BF.
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@
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)))
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 * <
The code, without directionals, is read as $:i*2_%.
$reads an integer x, stack contains{x}.:duplicates it, stack contains{x,x}.iincrements the top of stack, stack contains{x,x+1}.*multiplies the top two stack values, stack contains{x*(x+1)}.2pushes 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 equationx*(x+1)/2.
,,,, 6 bytes
:1+×2÷
Explanation
:1+×2÷
: ### duplicate
1+ ### add 1
× ### multiply
2÷ ### divide by 2
If I implement range any time soon...
rΣ
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]
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.
Clojure, 16 bytes
#(/(*(inc %)%)2)
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..)
Java (OpenJDK 8), 10 bytes
a->a++*a/2
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
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
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
𝐈𝐬
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
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
>¹*;
How it works
> #input + 1
¹* #get original input & multiply
; #divide by two
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
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~`
Probably can go shorter, but late now...
Terrapin Logo, 16 bytes
OP (1+:N)*(:N/2)
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:
Explanation
The highlighted text shows the current stack (growing from left to right), assuming the user input is 5:
Input a number and push it onto stack
5
Duplicate this number on the stack
5 5
Push 1 (the size of the dark red area) onto stack
5 5 1
5 6
30
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
Divide the second number on the stack by the first one
15
Pop and output the top number (interpreted as number)
[empty]
By inserting a white area, the transition is a nop, the black traps our cursor. This ends execution of the program.
Perl 6, 11 bytes
{[+] 1..$_}
{ } 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!
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}
Casio Basic, 9 bytes
(n+1)n/2
8 bytes for the code, +1 to add n as parameter.
Starry, 27 22 bytes
5 bytes saved thanks to @miles!
, + + ** + *.
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
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@#&
Julia, 10 bytes
n->n*-~n/2
11 bytes (works also on Julia 0.4)
n->sum(1:n)
Swift, 13 bytes
Anonymous function:
{$0*($0+1)/2}
You can call it like this:
print({$0*($0+1)/2}(5))
Husk, 1 byte
Σ
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
Or if input can be taken as a character code:
><>, 9 bytes
i:1+2,*n;
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),:+
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
PowerShell, 22 18 bytes
param($n)$n*++$n/2
Saved 4 bytes thanks to FryAmTheEggman. Uses Gauss' formula. Ho-hum.
JavaScript (ES6), 10 bytes
n=>n*++n/2
Example
let f =
n=>n*++n/2
console.log(f(5))






