85
\$\begingroup\$

I'm honestly surprised that this hasn't been done already. If you can find an existing thread, by all means mark this as a duplicate or let me know.

Input

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

Output

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

Example

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

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

Leaderboard

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

var QUESTION_ID=133109,OVERRIDE_USER=69148;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
10
  • 5
    \$\begingroup\$ Closely related \$\endgroup\$ Commented Jul 18, 2017 at 20:36
  • \$\begingroup\$ @FryAmTheEggman Sorry - had a bit of a brain fart there. I see what you mean. \$\endgroup\$
    – Gareth
    Commented Jul 18, 2017 at 20:45
  • 2
    \$\begingroup\$ @Aaron you got ninja'd by Husk, which was just posted with a 1 byte solution \$\endgroup\$
    – Mayube
    Commented Jul 18, 2017 at 21:35
  • 7
    \$\begingroup\$ I suggest a stack snippet. \$\endgroup\$
    – user58826
    Commented Jul 19, 2017 at 11:42
  • 1
    \$\begingroup\$ Related: minecraftforum.net/forums/off-topic/… \$\endgroup\$ Commented Jul 27, 2017 at 12:20

223 Answers 223

1
2
3 4 5
8
4
\$\begingroup\$

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

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Using the other math-approach ((n^2+n)/2) is also 7 bytes: ::*+2,n \$\endgroup\$
    – steenbergh
    Commented Jul 19, 2017 at 8:18
4
\$\begingroup\$

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;
\$\endgroup\$
1
  • \$\begingroup\$ I guess a for too: for(;$argn;$s+=$argn--);echo$s; \$\endgroup\$
    – Progrock
    Commented Oct 13, 2019 at 17:12
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Actually, one-operand imul ecx or mul ecx would work and save a byte in the closed-form implementation. I didn't spot that right away; I was about to comment that it was optimal for both performance and code-size before realizing that an implicit eax operand was fine. \$\endgroup\$ Commented Jul 22, 2017 at 8:42
  • \$\begingroup\$ I wondered if add+loop would be shorter than imul while looking at the other answer. Handy that there's a standard calling convention that passes the first arg in ecx \$\endgroup\$ Commented Jul 22, 2017 at 8:45
  • 1
    \$\begingroup\$ Wow, I can't believe I missed the one-operand form! I should really know by now not to say things like "cannot be beat". When will I learn?! Thanks, @Peter. \$\endgroup\$
    – Cody Gray
    Commented Jul 22, 2017 at 11:08
4
\$\begingroup\$

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!

\$\endgroup\$
4
\$\begingroup\$

Python 2, 16 bytes

lambda n:-~n*n/2

Try it online!

\$\endgroup\$
8
  • 2
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ Commented Jul 19, 2017 at 16:56
  • \$\begingroup\$ Is there any problem in my answer? \$\endgroup\$ Commented Jul 19, 2017 at 17:03
  • 1
    \$\begingroup\$ You can save a byte by changing it to print(n+1)*n/2 (Someone might already have print(n+1)*n/2 as answer though) \$\endgroup\$
    – Adalynn
    Commented Jul 19, 2017 at 17:22
  • 3
    \$\begingroup\$ Where is n defined? \$\endgroup\$ Commented Jul 20, 2017 at 8:59
  • 6
    \$\begingroup\$ Our consensus is that submissions must be full programs or functions, of which yours is neither (yours is a snippet, as in it needs other code to run properly). You could fix it by counting the assignment of input() to n in your submission or changing it to a function/lambda that returns the result. By the way, welcome to PPCG! \$\endgroup\$ Commented Jul 20, 2017 at 18:27
4
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ Why not sum(randIntNoRep(1,Ans? \$\endgroup\$
    – lirtosiast
    Commented Aug 25, 2017 at 0:33
  • \$\begingroup\$ @lirtosiast True, that didn't occur to me. \$\endgroup\$
    – Timtech
    Commented Aug 25, 2017 at 2:21
4
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

Ohm, 2 bytes

Try it online!

Explanation

@Σ

    implicit input
@   inclusive range [1..input]
 Σ  sum
    implicit output
\$\endgroup\$
3
\$\begingroup\$

PowerShell, 22 18 bytes

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

Try it online!

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

\$\endgroup\$
1
  • \$\begingroup\$ @FryAmTheEggman You'd think so, and you'd be right. :p \$\endgroup\$ Commented Jul 18, 2017 at 20:53
3
\$\begingroup\$

WendyScript, 17 bytes

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

f(100) // => 5050

Try it online!

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

Brachylog, 2 bytes

⟦+

Try it online!

Explanation

⟦      Range: [0, …, Input]
 +     Sum:   0 + … + Input
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
5
  • \$\begingroup\$ Isn't there decrement peg? I'm pretty sure it is either ) or ( \$\endgroup\$ Commented Jul 19, 2017 at 8:00
  • \$\begingroup\$ @RomanGräf I literally used that peg in another challenge like 5 minutes before writing this answer, I'm an idiot :P \$\endgroup\$
    – Mayube
    Commented Jul 19, 2017 at 8:32
  • \$\begingroup\$ I also forgot that despite being typeable on my UK keyboard layout, £ is not a 1-byte character. Changed division character to , \$\endgroup\$
    – Mayube
    Commented Jul 19, 2017 at 8:35
  • \$\begingroup\$ I don't thinm editing the name of a feature after the realese of the challenge is valid tho... \$\endgroup\$ Commented Jul 19, 2017 at 8:36
  • \$\begingroup\$ @RomanGräf Community Consensus allows newer versions of languages, and given this is not at all a change specific for this challenge (having the division operator be 2 bytes is a pretty big issue), I don't think it's a problem \$\endgroup\$
    – Mayube
    Commented Jul 19, 2017 at 9:07
3
\$\begingroup\$

Bash, 26, 19 bytes

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

Try it online!

19 bytes for the code, thanks to rexkogitans.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ echo $[($1+1)*$1/2] 19 bytes \$\endgroup\$ Commented Jul 19, 2017 at 16:32
  • \$\begingroup\$ @rexkogitans Edited! Thanks \$\endgroup\$ Commented Jul 21, 2017 at 16:34
3
\$\begingroup\$

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
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Actually, I think you saved 9 bytes thanks to Gauss ;) But thanks for the credit! \$\endgroup\$ Commented Jul 18, 2017 at 21:10
3
\$\begingroup\$

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
\$\endgroup\$
5
  • \$\begingroup\$ You might want to make TI-BASIC link to something. \$\endgroup\$
    – Adalynn
    Commented Jul 30, 2017 at 17:52
  • \$\begingroup\$ TI-BASIC is the language that is used on most Texas instruments graphics calculators; what should I link to? \$\endgroup\$
    – user1812
    Commented Jul 31, 2017 at 18:40
  • \$\begingroup\$ Or remove the brackets. \$\endgroup\$
    – Adalynn
    Commented Jul 31, 2017 at 18:48
  • \$\begingroup\$ Alternatively sum(randIntNoRep(1,N \$\endgroup\$
    – Oki
    Commented Sep 9, 2017 at 11:50
  • \$\begingroup\$ Wow! Didnt think of that :D It is unfortunate that randIntNoRep() is 2 bytes not 1. \$\endgroup\$
    – user1812
    Commented Sep 9, 2017 at 22:37
3
\$\begingroup\$

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 
\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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!

\$\endgroup\$
8
  • 2
    \$\begingroup\$ Wouldn't this be shorter with a different name? Like s instead of sum? Also, I think you could remove some spaces \$\endgroup\$
    – DJMcMayhem
    Commented Jul 18, 2017 at 21:14
  • \$\begingroup\$ Yep, just submitted it for speed, thanks for the notice! \$\endgroup\$ Commented Jul 18, 2017 at 21:15
  • 1
    \$\begingroup\$ Hi and welcome to PPCG! Our standard methods of input does not include the value being stored in a variable. I think you should be able to get a similar score using an unnamed lambda function. I think you can also do better by using Gauss' formula. I hope you enjoy your time here! \$\endgroup\$ Commented Jul 18, 2017 at 21:28
  • 2
    \$\begingroup\$ You still need to use a function. A snippet that assumes you set a variable beforehand and sets a new variable, like what you have, is not allowed. In Ruby, this is achieved with ->n{your code}, and it will automatically return whatever you input. Run with ->n{your code}.call(5) \$\endgroup\$
    – Value Ink
    Commented Jul 18, 2017 at 21:56
  • 3
    \$\begingroup\$ You don't need the .call(5). That's just an example of how you'd call the function. For example, p ->n{your code}.call(5) prints the result of the function for n=5. \$\endgroup\$
    – Value Ink
    Commented Jul 18, 2017 at 23:31
3
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ :/ 64 \$\endgroup\$
    – ASCII-only
    Commented Jan 30, 2019 at 9:38
3
\$\begingroup\$

tinylisp, 30 bytes

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

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Vyxal s, 1 byte

ɾ

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

Try it!

\$\endgroup\$
4
  • \$\begingroup\$ Wouldn't this count as 2 since the flags are counted? \$\endgroup\$
    – Underslash
    Commented May 12, 2021 at 1:36
  • \$\begingroup\$ @Underslash flags aren't counted \$\endgroup\$
    – Wasif
    Commented May 12, 2021 at 1:54
  • \$\begingroup\$ Unless I'm remembering wrong, aren't flags counted as a byte each because you can abstract away code with them? \$\endgroup\$
    – Underslash
    Commented May 12, 2021 at 6:48
  • 1
    \$\begingroup\$ @Underslash Nope. Instead, "Vxyal s" is considered an entirely separate language from "Vyxal". I'm not sure what you mean by "abstract away code", but overuse of command like flags to store code makes the answer violate the standard loophole "using a made-up language designed specifically for the challenge" \$\endgroup\$ Commented May 17, 2021 at 3:07
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

F# (.NET Core), 12 17 bytes

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

Try it online!

\$\endgroup\$
6
  • \$\begingroup\$ Welcome to Code Golf! I don't know F#, but is this really a valid function definition? It doesn't look like a complete declaration or a expression. \$\endgroup\$
    – alephalpha
    Commented Feb 1, 2023 at 2:54
  • 1
    \$\begingroup\$ I think this should be either let s x=(x+1)*x/2 or fun x->(x+1)*x/2. ` x=(x+1)*x/2` is just a part of let s x=(x+1)*x/2. \$\endgroup\$
    – alephalpha
    Commented Feb 1, 2023 at 3:01
  • \$\begingroup\$ Personally I agree with you and that's what I would consider a full submission. However looking at the C# and ES6 submissions, the line between "function" (just the math) and "function" (everything needed to call it for any n) is a bit blurred? \$\endgroup\$
    – dtanku
    Commented Feb 1, 2023 at 14:55
  • \$\begingroup\$ You either declare a function, or write a expression whose value is a function. The C# and ES6 submissions are lambda expressions, equivalent to fun x->(x+1)*x/2 in F#. \$\endgroup\$
    – alephalpha
    Commented Feb 1, 2023 at 23:59
  • \$\begingroup\$ Fair enough. FWIW, the lambda solution is worse, what with needing fun and 2 extra brackets and still needs whitespace to come close to a similar size. Edited to include let s (+5). \$\endgroup\$
    – dtanku
    Commented Feb 2, 2023 at 1:29
3
\$\begingroup\$

AArch64 machine code, 12 bytes

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

Equivalent to:

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

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

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

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

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

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

It should work even in big-endian mode :)

\$\endgroup\$
2
\$\begingroup\$

Positron, 27 bytes

Positron is a new practical language by @HyperNeutrino.

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

Try it online!

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Yay I'm happy :D \$\endgroup\$
    – hyperneutrino
    Commented Jul 19, 2017 at 1:25
2
\$\begingroup\$

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)

\$\endgroup\$
2
  • \$\begingroup\$ You can save 2 more bytes with {[+] ^$_} \$\endgroup\$
    – Massa
    Commented Sep 8, 2017 at 14:12
  • \$\begingroup\$ @Massa That would exclude the $_ as it is short for 0 ..^ $_, so it would need to be ^$_+1 which is exactly the same length as what I have. \$\endgroup\$ Commented Sep 8, 2017 at 15:10
2
\$\begingroup\$

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

\$\endgroup\$
1
2
3 4 5
8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.