title: Sum of all integers from 1 to n

text:
# Question
Title: Sum of all integers from 1 to n
I'm honestly surprised that this hasn't been done already. If you can find an existing thread, by all means mark this as a duplicate or let me know.

# Input

Your input is in the form of any positive integer greater than or equal to 1.

# Output

You must output the sum of all integers between and including 1 and the number input.

# Example

```
 In: 5
     1+2+3+4+5 = 15
Out: 15

```

OEIS A000217 — Triangular numbers: a(n) = binomial(n+1,2) = n(n+1)/2 = 0 + 1 + 2 + ... + n.

# Leaderboard

Run the code snippet below to view a leaderboard for this question's answers. (Thanks to programmer5000 and steenbergh for suggesting this, and Martin Ender for creating it.)

```
var QUESTION_ID=133109,OVERRIDE_USER=69148;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Pyth, 2 bytes

```
sS

```

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

# Answer
# 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`.
> 36 votes

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

```
> 25 votes

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

```

Add the top two numbers

```
5 6

```

Multiply the top two numbers

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

> Original file (far too small for here):
> 25 votes

# Answer
# Oasis, 3 bytes

```
n+0

```

Try it online!

## How it works

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

```
> 24 votes

# Answer
## JavaScript (ES6), 10 bytes

```
n=>n*++n/2

```

### Example

```
let f =

n=>n*++n/2

console.log(f(5))
```
> 20 votes

# Answer
# 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]

```
> 19 votes

# Answer
# Python 2, ~~24~~ 16 bytes

*-8 bytes thanks to FryAmTheEggman.*

```
lambda n:n*-~n/2

```

Try it online!
> 12 votes

# Answer
# 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.
> 12 votes

# Answer
# C# (.NET Core), 10 bytes

```
n=>n++*n/2

```

Try it online!
> 11 votes

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

```
> 10 votes

# Answer
# 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.
> 10 votes

# Answer
# Java (OpenJDK 8), 10 bytes

```
n->n++*n/2

```

Try it online!
> 10 votes

# Answer
# Haskell, 13 bytes

This is the shortest (I ~~think~~thought):

```
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!
> 9 votes

# Answer
# APL, 3 bytes

```
+/⍳

```

Try it online!

`+/` \- sum (reduce `+`),  \- range.
> 8 votes

# Answer
# 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.
> 8 votes

# Answer
# 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`
> 8 votes

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

```
> 7 votes

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

```
> 7 votes

# Answer
# 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!
> 7 votes

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

# Answer
# MATL, 2 bytes

```
:s

```

Try it online!

Not happy smiley.
> 6 votes

# Answer
# dc, 7 bytes

```
d1+*2/p

```

OR

```
d2^+2/p

```

OR

```
dd*+2/p

```

Try it online!
> 6 votes

# Answer
# 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!
> 6 votes

# Answer
# ,,,, 6 bytes

```
:1+×2÷

```

## Explanation

```
:1+×2÷

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

```

If I implement range any time soon...
> 5 votes

# Answer
# 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 `1`s to its left plus another `1` for the `1` itself, thus counting from `1` to `n`, summing the values implicitly.
> 5 votes

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

```
> 5 votes

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

```
> 5 votes

# Answer
# 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.
> 5 votes

# Answer
# 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 STDIN
* `2`: 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;
}

```
> 5 votes

# Answer
# \>\<\>, 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!
> 4 votes

# Answer
# 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;

```
> 4 votes

# Answer
# 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.
> 4 votes

# Answer
# Python 2, 16 bytes

```
lambda n:-~n*n/2

```

Try it online!
> 4 votes

# Answer
# Triangular, 10 bytes

```
$\:_%i/2*<

```

Ungolfed:

```
   $
  \ :
 _ % i
/ 2 * <

```

Try it online!

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

* `$` reads an integer *x*, stack contains `{x}`.
* `:` duplicates it, stack contains `{x,x}`.
* `i` increments the top of stack, stack contains `{x,x+1}`.
* `*` multiplies the top two stack values, stack contains `{x*(x+1)}`.
* `2` pushes 2 to the stack, stack contains `{x*(x+1),2}`.
* `_` divides the top two stack values, stack contains `{x*(x+1)/2}`.
* `%` prints the top of stack, the equation `x*(x+1)/2`.

Idea thanks to caird, who asked me to post.
> 4 votes

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

```
> 4 votes

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

```
> 4 votes

# Answer
# 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!
> 4 votes

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

```
> 4 votes

# Answer
# PowerShell, ~~22~~ 18 bytes

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

```

Try it online!

*Saved 4 bytes thanks to FryAmTheEggman*. Uses Gauss' formula. Ho-hum.
> 3 votes

# Answer
# Ohm, 2 bytes

Try it online!

## Explanation

```
@Σ

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

```
> 3 votes

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

```
> 3 votes

# Answer
## 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!**
> 3 votes

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

```
> 3 votes

# Answer
# WendyScript, 17 bytes

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

f(100) // => 5050

```

Try it online!
> 3 votes

# Answer
# 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.
> 3 votes

# Answer
# Bash, ~~26~~, 19 bytes

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

```

Try it online!

19 bytes for the code, thanks to rexkogitans.
> 3 votes

# Answer
# Brachylog, 2 bytes

```
⟦+

```

Try it online!

### Explanation

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

```
> 3 votes

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

```
> 3 votes

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

```
> 3 votes

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

```
> 3 votes

# Answer
# 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.
> 3 votes

# Answer
# Vyxal `s`, 1 byte

```
ɾ

```

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

Try it!
> 3 votes

# Answer
# tinylisp, 30 bytes

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

```

Try it online!
> 3 votes

# Answer
# 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.
> 3 votes

# Answer
# F# (.NET Core), ~~12~~ 17 bytes

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

```

Try it online!
> 3 votes

# Answer
# 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 const uint32_t d[] __attribute__((section(".text"))) = {
  0x9b000000, // madd x0, x0, x0, x0
  0xd341fc00, // lsr  x0, x0, #1
  0xd65f03c0, // ret
};
int main(void) {
  uint64_t (*f)(uint32_t) = d;
  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 :)
> 3 votes

# Answer
# R, 13 bytes

```
sum(1:scan())

```

Saved 9 bytes thanks to Giuseppe and Max Lawnboy.
> 2 votes

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

```
> 2 votes

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

```
> 2 votes

# Answer
# 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*
> 2 votes

# Answer
# Positron, 27 bytes

Positron is a new practical language by @HyperNeutrino.

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

```

Try it online!
> 2 votes

# Answer
# 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)
> 2 votes

# Answer
# 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...
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# 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. :)
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# 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.
> 2 votes

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

```
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# Röda, 13 bytes

```
{seq 1,_|sum}

```

Try it online!
> 2 votes

# Answer
# 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!
> 2 votes

# Answer
# Pyt, 1 byte

Try it online!

Explanation:

```
               implicit input
 △             compute the nth triangle number

```
> 2 votes

# Answer
# brainfuck, 14 bytes

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

```

Try it online!

Takes input as character code, outputs as unary null bytes
> 2 votes

# Answer
# 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!
> 2 votes

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

```
n=>n*++n/2

```

Try it online!
> 2 votes

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

```
> 2 votes

# Answer
# 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!
> 2 votes

# Answer
# Hexagony, 16 bytes

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

```

Try it online! Try it online differently!
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# Fourier, 9 bytes

```
I~_^*_/2o

```

Try it online!
> 2 votes

# Answer
# flax, 2 bytes

```
Σκ

```

Try It Online!

## Explanation

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

```
> 2 votes

# Answer
## MSWLogo, 26 bytes

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

```
> 2 votes

# Answer
# Vyxal `Rs`, 0 bytes

```

```

Try it Online!

Lol
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# 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:

* 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.
> 2 votes

# Answer
`awk`, **18** bytes

```
jot 50 |

```

> ```
> awk '$_*=$++_++/(_+_--)'
>
> ```

```
1
3
6
10
15
21
28
36
45
55
66
78
91
105

```
> 2 votes

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

```
> 2 votes

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

```
> 2 votes

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

```
> 2 votes

# Answer
# Erlang 19 bytes

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

```
> 2 votes

# Answer
# 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
> 2 votes

# Answer
# 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.
> 2 votes

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

```
> 2 votes

# Answer
# (,) `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
> 2 votes

# Answer
# bc, 9 bytes

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

```

Try it online!

Weird how some shell solutions call `bc` instead of just writing `bc` code.
> 2 votes

# Answer
# 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
> 1 votes

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

```
> 1 votes

# Answer
# Japt `-x`, ~~3~~ 1 bytes

```
ò

```

## Explanation:

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

```

Try it online!
> 1 votes

# Answer
# 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)

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Clojure, ~~31~~ ~~23~~ 16 bytes

*8 bytes saved thanks to @cliffroot*

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

```

Try it online!
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Swift, 13 bytes

Anonymous function:

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

```

You can call it like this:

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

```

Try it online!
> 1 votes

# Answer
# Mathematica, 9 bytes

```
#(#+1)/2&

```

or, at 11 bytes,

```
Tr@Range@#&

```
> 1 votes

# Answer
# Ly, ~~26~~ 7 bytes

```
n:1+*2/u

```

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

# Answer
# , 40 bytes

```
3.70060101002000120300026040230503045054

```

Try it online!
> 1 votes

# Answer
# Tcl, 27 bytes

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

```

Try it online!
> 1 votes

# Answer
# Casio Basic, 9 bytes

```
(n+1)n/2

```

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

# Answer
# Factor, 12 bytes

```
[ iota sum ]

```

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

# Answer
# Terrapin Logo, 16 bytes

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

```
> 1 votes

# Answer
# GolfScript, ~~7~~ 6 bytes

```
~.)2/*

```

Try it online!
> 1 votes

# Answer
# Commentator, 22 bytes

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

```

Try it online!
> 1 votes

# Answer
# \>\<\>, ~~20~~ 15 bytes

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

```

*@notatree saved me a couple bytes!*

Try it online!
> 1 votes

# Answer
# Pip, 7 bytes

```
a*++a/2

```

Try it online!
> 1 votes

# Answer
# Common Lisp, 26 bytes

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

```
> 1 votes

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

```
> 1 votes

# Answer
# 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
> 1 votes

# Answer
# 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)

```
> 1 votes

# Answer
# Befunge, 9 bytes

```
&:1+*2/.@

```

Try it online!
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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]

```
> 1 votes

# Answer
# Java, 10 bytes

```
n->n*-~n/2

```

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

# Answer
# 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!
> 1 votes

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

```
> 1 votes

# Answer
# Emojicode, 50 bytes

```
➡➗✖➕1 2

```

Try it online!
> 1 votes

# Answer
# 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!
> 1 votes

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

```
> 1 votes

# Answer
# 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!
> 1 votes

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

```
> 1 votes

# Answer
## Python 3, 35 bytes

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

```
> 1 votes

# Answer
# C (gcc) 16 bytes

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

```

Try it online
> 1 votes

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

```
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~62~~ ~~40~~ 38 bytes

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

```

Try it online!
> 1 votes

# Answer
# Pyth - 2 Bytes

```
sS

```

Explanation:

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

```
> 1 votes

# Answer
# 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
> 1 votes

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

```
> 1 votes

# Answer
# 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.)
> 1 votes

# Answer
# Ahead, 6 bytes

```
IEK+O@

```

Try it online!
> 1 votes

# Answer
# @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`.
> 1 votes

# Answer
# MathGolf, 2 bytes

```
╒Σ

```

Try it online!

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

# Answer
## 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
> 1 votes

# Answer
# Gol\>\<\>, 7 bytes

```
I:P*2,h

```

Courtesy of JoKing

Try it online!

**8 bytes**

```
I::*+2,h

```

Try it online!
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Charcoal, 5 bytes

```
ＩΣ…·Ｎ

```

Try it online!

### Explanation:

```
 Σ        The sum of
  …·Ｎ     the inclusive range from 0 to input
Ｉ          converted to a string

```

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

# Answer
## Clojure - 19 bytes

`#(apply +(range %))`

Boring answer is boring...
> 1 votes

# Answer
# Rust, 12 bytes

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

```

Try it online!

Anonymous function.
> 1 votes

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

```
> 1 votes

# Answer
# MAWP, 8 bytes

```
@!1+*2$:

```

Try it!

Old solution that manually loops through integers:

# MAWP, 13 bytes

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

```

Try it!
> 1 votes

# Answer
# 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
> 1 votes

# Answer
## \<\>^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
> 1 votes

# Answer
# Python 3, 26 bytes

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

```

Try it online!

Bewildered this isn't here yet.
> 1 votes

# Answer
# APOL, 18 bytes

`v(0);ⅎ(⧣ ∆(0 ∈));⁰`
> 1 votes

# Answer
# 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
> 1 votes

# Answer
# Factor \+ `math.unicode`, 12 bytes

```
[ [1,b] Σ ]

```

Try it online!

Posting this here because the other Factor answer is incorrect.
> 1 votes

# Answer
# J-uby, 7 bytes

```
:+|:sum

```

Try it online!
> 1 votes

# Answer
# Desmos, 13 bytes

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

```

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

Try It On Desmos!
> 1 votes

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

```
> 1 votes

# Answer
# Prolog (SWI), 18 bytes

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

```

Try it online!

Simple application of the formula
> 1 votes

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

```
> 1 votes

# Answer
# PowerShell, 22 bytes

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

```

Try it online!
> 1 votes

# Answer
# 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!
> 1 votes

# Answer
# Thunno 2 `S`, 1 byte

```
R

```

Attempt This Online!

## Thunno 2, 2 bytes

```
RS

```

Attempt This Online!

Pretty simple.
> 1 votes

# Answer
# Vyxal `Rs`, 0 bytes

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

```

```

Try it Online!

Vyxal has useful flags.
> 1 votes

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

```
> 1 votes

# Answer
# Swift, ~~39~~ 28 bytes

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

```

Fairly self-explanatory.
> 1 votes

# Answer
# Uiua, 15 bytes

```
/+⇡+1parse&sc

```

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

Uiua Pad
> 1 votes

# Answer
# Scratch, 31 bytes

Try it here

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

```
> 1 votes

# Answer
# Tcl, 36 bytes

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

```

Try it online!
> 0 votes

# Answer
# Tcl, 29 bytes

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

```

Try it online!
> 0 votes

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

```
> 0 votes

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

```
> 0 votes

# Answer
# Scala, 12 bytes

### Gauss sum (12 bytes):

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

```

### Naive version (14 bytes):

```
n=>1.to(n).sum

```
> 0 votes

# Answer
# Clojure, 28 bytes

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

```
> 0 votes

# Answer
# JavaScript (Node.js), 12 bytes

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

```

Try it online!
> 0 votes

# Answer
# Clojure, 16 bytes

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

```
> 0 votes

# Answer
# Groovy, 11 bytes

```
{it*++it/2}

```

Try it online!

---

The input is not modified by rules of Groovy clsures.
> 0 votes

# Answer
# PHP, 35 34 32 25 bytes

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

```

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

# Answer
# 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!
> 0 votes

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

```
> 0 votes

# Answer
# Swift 3, 60 Bytes

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

```

Try it online!
> 0 votes

# Answer
# Math++, 13 bytes

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

```
> 0 votes

# Answer
## Matlab/Octave, 12 bytes

```
@(n)sum(1:n)

```
> 0 votes

# Answer
# Perl 5, 11 bytes

10 bytes of code + 1 for -p

```
$_*=$_++/2

```

Try it online!
> 0 votes

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

```
> 0 votes

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

```
> 0 votes

# Answer
# 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!
> 0 votes

# Answer
# 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)`.
> 0 votes

# Answer
# Windows batch, ~~57~~ 21 bytes

Inspired by J42161217

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

```
> 0 votes

# Answer
# 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..
> 0 votes

# Answer
# Broccoli, ~~35~~, 33 bytes

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

```

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

```
(t 10)

```
> 0 votes

# Answer
# Pyt, 2 bytes

```
řƩ

```

Try it online!

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

golfed by mudkip
> 0 votes

# Answer
# 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!
> 0 votes

# Answer
# Aheui (esotope), 33 bytes

```
방빠받반타다따반나망해

```

Try it online!
> 0 votes

# Answer
# 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}`
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# Tir, 4 bytes

```
{∟+}

```

Try it online!

## Explanation

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

```
> 0 votes

# Answer
# Fynyl, 5 bytes

```
{rf+}

```

Try it online!

## Explanation

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

```
> 0 votes

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

```
> 0 votes

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

```
> 0 votes

# Answer
# , 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;}`
> 0 votes

# Answer
# 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;}`
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
## , 2 bytes

```
+R

```

## Explanation

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

```
> 0 votes

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

```
> 0 votes

# Answer
# 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)
> 0 votes

# Answer
# Arn, 3 bytes

```
+\~

```

Try it!

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

# Answer
# 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!
> 0 votes

# Answer
# Duocentehexaquinquagesimal, 10 bytes

```
1ËвáýŸÚ¦˜Í

```

Try it online! I/O as characters.
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# 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}\\$.
> 0 votes

# Answer
# 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!
> 0 votes

# Answer
# 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]

```
> 0 votes

# Answer
# Chocolate, 1 byte

Try it online!
> 0 votes

# Answer
# Knight, 11 bytes

```
O/*+1=xPx 2

```

Try it online!
> 0 votes

# Answer
# Arturo, 12 bytes

```
$=>[∑1..&]

```

Try it
> 0 votes

# Answer
# ARBLE, 15 bytes

```
sum(range(1,n))

```

Uninteresting answer.

Try it online!
> 0 votes

# Answer
## 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:
> 0 votes

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

```
> 0 votes

# Answer
# Desmoslang Assembly, 11 Bytes

`IS*.5(D+1OT`
> 0 votes

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

```
> 0 votes

---
Tags: code-golf, math, number
---


title: German pharmacy payment

text:
# Question
Title: German pharmacy payment
Your task is to calculate the amount you have to pay for prescribed medication at a pharmacy in Germany. The amount is simply based on the full price of the item, which will be your input. It is a decimal number with exactly two fractional digits (ex. 5.43). You can assume it's strictly positive. Your task is to calculate the amount a customer has to pay, according to this function:

$$ A(x)=\begin{cases} x&\text{if } x\le 5\\ 5&\text{if } 5\le x \le 50\\ 0.1x&\text{if }50\le x \le 100\\ 10&\text{if }100 \le x \end{cases} $$ or equivalently $$ A(x)=\min(x,\min(\max(0.1x,5),10)) $$

The result must be **rounded** to two decimal places (half up). If these are 0, they may be skipped from the output. There must not be more than 2 decimal places. You can take numbers or strings as input and output, but be aware of inexact floating point representations.

Use a comma or a point as the decimal separator.

## Test cases

(Whitespace just for readability)

`5.00`, `5.0` and `5` are all ok.

```
  4.99  ->  4.99
  5.00  ->  5.00
  5.05  ->  5.00
  10.00 ->  5.00
  49.00 ->  5.00
  50.00 ->  5.00
  50.04 ->  5.00
  50.05 ->  5.01
  50.14 ->  5.01
  50.15 ->  5.02
  99.84 ->  9.98
  99.85 ->  9.99
  99.94 ->  9.99
  99.95 -> 10.00
 100.00 -> 10.00
1000.00 -> 10.00

```

# Answer
# Jelly, 14 bytes

```
÷⁵«⁵»5«+ȷ-4ær2

```

A monadic Link that accepts the full price as a float and outputs the charge as a float.

**Try it online!**

### How?

```
÷⁵«⁵»5«+ȷ-4ær2 - Link: Full Price           P
÷⁵             - divide Full Price by 10    P/10
  «⁵           - minimum with 10            min(10,P/10)
    »5         - maximum with 5             max(5,min(10,P/10))
      «        - minimum with Full Price    min(P,max(5,min(10,P/10)))
       +ȷ-4    - add 0.0001 (catering for banker's rounding effects below)
           ær2 - round to two decimal places

```
> 8 votes

# Answer
# APL+WIN, 21 bytes

Prompts for input

```
2⍕(n⌊((.1×n←⎕)⌈5))⌊10

```

Try it online! Thanks to Dyalog Classic
> 6 votes

# Answer
# , 39 bytes

```
\(x)round(.001+min(x,max(.1*x,5),10),2)

```

Basically using the formula given by the OP.

-5 bytes thanks to @doubleunary

-3 bytes and fix a rounding error thanks to @NickKennedy

-6 bytes since the OP removed the requirement for exactly 2 decimal places.

Try it online!
> 6 votes

# Answer
# APL (Dyalog Unicode), 13 bytes

```
2⍕⊢⌊10⌊5⌈.1×⊢

```

Try it online!

Tacit prefix function. Takes input as number. Thanks to Graham for original APL solution.

### How it works:

```
2⍕⊢⌊10⌊5⌈.1×⊢ ⍝ Anonymous, tacit function.
         .1×⊢ ⍝ 0.1x
       5⌈      ⍝ max with 5
    10⌊        ⍝ min with 10
   ⊢⌊          ⍝ min with x (as a fork)
2⍕            ⍝ format with 2 decimal places

```
> 4 votes

# Answer
# JavaScript (Node.js), 40 bytes

```
x=>Math.min(x,x<50?5:(x*10+.5|0)/100,10)

```

Try it online!

# Python 3, 45 bytes

```
lambda x:round(sorted([x,5,10,x/9.999])[1],2)

```

Try it online!

-2 from PattuX
> 3 votes

# Answer
# Retina 0.8.2, ~~95~~ 92 bytes

```
\.

.+
$*
^(.{1000}(?=.{8995})|.(.{499,998})(?=\2{9}....)|.{0,500}).*
00$.1
0*(.+)(..)
$1.$2

```

Try it online! Link includes test cases. Explanation:

```
\.

```

Multiply by `100`.

```
.+
$*

```

Convert to unary.

```
^(.{1000}(?=.{8995})|.(.{499,998})(?=\2{9}....)|.{0,500}).*
00$.1

```

Calculate the amount to pay, with two `0`s prefixed in case the amount is less than `100`.

```
0*(.+)(..)
$1.$2

```

Divide by `100`.

The disjunctions are as follows:

* `.{1000}(?=.{8995})` Any amount over `9994` becomes `1000`.
* `.(.{499,998})(?=\2{9}....)` Any amount over `4999` becomes a tenth of its value. `.(.{499,998})` is the amount to pay, between `500` and `999`, but the input has to match that value plus `9` times `1` less than that value plus `4`, which equals `10` times that minus `5`, thus rounding half up.
* `.{0,500}` Any amount below `500` is unchanged, but amounts between `500` and `4999` become `500`.
> 2 votes

# Answer
# Google Sheets / Microsoft Excel, 31 bytes

`=fixed(min(10,A1,max(5,A1/10)))`

Put the input in cell `A1` and the formula in `B1`. The `fixed()` function also takes care of rounding.

Equivalent JavaScript (rounding issue, non-competing, **45 bytes**):

`x=>Math.min(10,x,Math.max(5,x/10)).toFixed(2)`
> 2 votes

# Answer
# Ruby, ~~42~~ 36 bytes

```
->a{[a,[a/10,5].max,10].min.round 2}

```

Try it online!

# Ruby, 38 bytes

Formatted as per initial requirement:

```
->a{"%.2f"%[a,[a/9.999,5].max,10].min}

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6), 45 bytes

```
x=>~~(Math.min(x*10,x<50?50:x,100)*10+.5)/100

```

Try it online!

---

## 40 bytes

This one works in theory, but fails on some test cases because of rounding errors.

```
x=>Math.min(x,x<50?5:x/10,10).toFixed(2)

```

Try it online!
> 1 votes

# Answer
# Python, 41 bytes

```
lambda x:min(max(5,(x*20+1)//2/100),x,10)

```

Attempt This Online!

Straight-forward implementation of OP's formula. For the rounding it uses floor division resulting in integer-valued floats which - unlike tenths - are guaranteed to be represented exactly.
> 1 votes

# Answer
# Charcoal, 21 bytes

```
ＮθＩ⌊⟦θχ⌈⟦⁵∕⌊⁺·⁵×θχ¹⁰⁰

```

Try it online! Link is to verbose version of code. Explanation: Port of the formula given in the question, but with rounding as required. I checked all inputs from `50.00` to `99.99` and none of them had any rounding errors; even though for example `64.35*100` does not result in `6435`, `64.35*10` does result in `643.5`, which is then rounded to `644`, with a final result of `6.44`.

```
Ｎθ                      First input as a number
                θ       First input
               ×        Multiplied by
                 χ      Literal integer `10`
            ⁺           Plus
             ·⁵         Literal number `0.5`
           ⌊            Floor
          ∕             Divided by
                  ¹⁰⁰   Literal integer `100`
         ⁵              Literal integer `5`
        ⟦               Make into list
       ⌈                Take the maximum
      χ                 Predefined variable `10`
     θ                  Input number
    ⟦                   Make into list
   ⌊                    Take the minimum
  Ｉ                     Cast to string
                        Implicitly print

```

Formatted to two decimal places also turns out to be 21 bytes:

```
Ｎθ﹪%.2f⌊⟦θχ⌈⟦⁵∕θ⁹·⁹⁹⁹

```

Try it online! Link is to verbose version of code. Explanation: Uses @PattuX's observation that dividing by `9.999` before rounding suffices to compensate for floating-point errors.
> 0 votes

# Answer
# Uiua 0.3.1, 16 bytes

```
↧↧↥5⍜×⁅100⊃÷∘10.

```

See it in action
> 0 votes

# Answer
# sclin, 26 bytes

```
dup.1*5|10,` &/100* |~100/

```

Try it on scline!

sclin's default real/rational number representation comes in handy here.

## Explanation

Prettified code:

```
dup .1* 5| 10,` &/ 100* |~ 100/

```

Assuming input *n*:

* `dup .1*` *n* * .1
* `5|` min with 5
* `10,` &/` min with 10 and *n*
* `100* |~ 100/` round 2 decimal places
> 0 votes

# Answer
# Wolfram Language (Mathematica), 36 bytes

```
#~Min~Max[.1#,5]~Min~10~Round~.01&@x

```

Alas, we cannot save an extra byte by using infix notation with `Max` because multiplication has a lower precedence than passing an argument, so `.1#~Max~5` is equivalent to `.1(#~Max~t)`, rather than `(.1#)~Max~t`.

Try it online!
> 0 votes

# Answer
# PARI/GP, 44 bytes

```
x->printf("%.2f",min(x,min(max(x/10,5),10)))

```

Attempt This Online!

A port of @Evargalo's R answer.

Prints the result to stdout.
> 0 votes

# Answer
# 05AB1E, 16 (or 25) bytes

```
T/5‚à‚Tªß4°z+2.ò

```

Try it online or verify all test cases.

This outputs `5.0` or `10.0` instead of `5.00` or `10.00`, like most other answers. To fix this, the following 9 bytes can be added:

```
т+0«6∍¦0Û

```

Try it online or verify all test cases.

**Explanation:**

```
T/        # Divide the (implicit) input by 10
5‚        # Pair it with 5
  à       # Pop and push the maximum of the pair
‚         # Pair it with the (implicit) input
 Tª       # Append 10 to this pair
   ß      # Pop and push the minimum of this triplet
4°        # Push 10**4: 10000
  z       # Pop and push 1/10000: 0.0001
   +      # Add it to the value
    2.ò   # Then (banker's) round it to 2 decimals

т+        # Add 100
  0«      # Append a trailing 0
    6∍    # Shorten it to length 6
      ¦   # Remove the leading 1
       0Û # Trim any leading 0s
          # (after which the result is output implicitly)

```
> 0 votes

# Answer
# AWK, 48 bytes

```
{y=$0/10;a=y>5?y>10?10:y:5>$0?$0:5;print a+1e-4}

```

Try it online!

---

Ungolfed :

```
BEGIN{
    OFMT = "%.2f"
}

func min(n,m){
    return m>n?n:m
}
func max(p,q){
    return p>q?p:q
}

{
    x=min($0,min(max(0.1*$0,5),10))+0.0001
    print $1, "->", x
}

```
> 0 votes

# Answer
# Scala 3, ~~106~~ 100 bytes

Saved 6 bytes thanks to @corvus\_192

---

Golfed version. Attempt This Online!

```
x=>BigDecimal(Seq(x,5,10,x/10).sorted.apply(1)+1e-6).setScale(2,BigDecimal.RoundingMode(4)).toDouble

```

Ungolfed version. Attempt This Online!

```
object Main {
  def f(x: Double): Double = {
    val sortedList = List(x, 5, 10, x/10).sorted
    BigDecimal(sortedList(1) + 1e-6).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble
  }

  def main(args: Array[String]): Unit = {
    println(f(90))
    println(f(210))
    println(f(16))
    println(f(4.21))
    println(f(5.05))
    println(f(25.15))
    println(f(25.654321))
    println(f(75))
    println(f(75.987654))
    println(f(1000))
  }
}

```
> 0 votes

# Answer
# Rust, 50 bytes

```
|x|(500f64.max(1e1*x).min(1e3).round()/1e2).min(x)

```

Try it online!
> 0 votes

# Answer
# \*\>\<\>, ~~90~~ 89 bytes

-1 byte by removing a semicolon that shouldn't have been there

I'm still trying to condense it using the dive `u` and rise `O` instructions, but in case I forget, here's a working version without them.

Requires running with the `-i` flag to receive input.

```
:5)?!\:5a*)?!\:9b*(?!\aa*:}*:a%:4)?v-   >$a*,n;
   ;n/    ;n5/    ;na/             \a$-+/

```

## Explanation

### x ≤ 5

```
:5)?!\
   ;n/

```

```
:         Duplicate the input
 5        Push 5 onto the stack
  )       Evaluate 5 > input
   ?!\   If true, redirect down
     /   Redirect left
   ;n     Print the input, and halt execution

```

### 5 ≤ x ≤ 50

```
:5a*)?!\
    ;n5/

```

```
:         Duplicate the input again
 5        Push 5 onto the stack
  a       Push 10 onto the stack
   *      Multiply the top to values, thus putting 50 onto the stack
    )     Evaluate 50 > input
     ?!\   If true, redirect down
       /   Redirect left
    ;n5    Push 5 onto the stack, print it, and halt execution

```

### 100 ≤ x

```
:aa*(?!\
    ;na/

```

```
:          Duplicate the input
 aa*       Multiply 10by 10, putting 100 onto the stack
    (      Evaluate 100 < input
     ?!\   If true, redirect down
       /   Redirect left
    ;na    Push 10 onto the stack, print it, and halt execution

```

### 50 ≤ x ≤ 100

In order to get half-up rounding, we multiply the input by 100 to make it an integer. From there we then round up/down to the nearest 10, and then divide by 1000 to get our final amount.

```
aa*:}*:a%:4)?v-   >$a*,n;
             \a$-+/

```

```
aa*                         Push 100 onto the stack
   :                        Duplicate the 100 on the stack
    }                       Shift the stack to the right, moving the duplicated 100 to the 0th index
     *                      Multiply the input by 100, replacing future instances of "input" with "input * 100"
      :                     Duplicate the input
       a                    Push 10 onto the stack
        %                   Push input modulo 10 onto the stack
         :                  Duplicate that value
          4                 Push 4 onto the stack
           )                Evaluate (input modulo 10) > 4
            ?v              If (input modulo 10) > 4 == true, redirect down
// If (input modulo 10) > 4 == true
             \              Redirect right
              a             Push 10 onto the stack
               $            Swap the top two values on the stack
                -           Subtract (input module 10) from 10
                 +          Add that to the input
                  /         Redirect up
// If (input modulo 10) > 4 == false
              -             Else, subtract (input module 10) from input
// After conditional
                  >         Force instruction pointer to the right
                   $        Swap the two values on the stack, making it [input, 100]
                    a*      Multiply the top value by 10, pushing 1000 onto the stack
                      ,     Divide the input by 1000
                       n;   Print the value and halt execution

```

Try it online!
> 0 votes

# Answer
# Desmos, ~~30~~ actually 35 bytes

A one-liner Desmos equation for once (thanks to Aiden Chow for the fix and optimization):

```
f(x)=round([x,5,10,x/10].sort[2],2)

```

Try it on Desmos!
> -1 votes

---
Tags: code-golf, number, arithmetic
---