Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is , answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17

Or as CSV:

a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17

Leaderboard

var QUESTION_ID=84260,OVERRIDE_USER=8478;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}
<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>

  • 25
    This is quite trivial, but not really simpler than, e.g., the Hello World catalog. Given that the ability to add integers is one of our two requirements for programming languages, I'd say it's worthwhile to have if properly specified. – Dennis Jul 2 '16 at 0:48
  • Can the answer take input with preceding zeros as default? e.g. 5 16 is inputted as 005 016 – FinW Dec 4 '16 at 11:56
  • @FinW Sure. As long as they don't get interpreted as octal. – Mendeleev Dec 4 '16 at 20:47

167 Answers 167

up vote 33 down vote accepted

Jelly, 1 byte

+

Try it online!

Also works in 05AB1E, Actually, APL, Braingolf, ,,, (Commata), Factor, Forth, Implicit, J, Julia, K, kdb+, Ly, MATL, Pyke, Deorst, and Q.

  • 2
    Also works in Swift. – Zacharý Sep 9 '17 at 14:23
  • 2
    Pyth as well @Zacharý – Stan Strum Oct 9 '17 at 0:18

Minecraft 1.10, 221 characters (non-competing)

See, this is what we have to deal with when we make Minecraft maps.

Aside: There's no way to take a string input in Minecraft, so I'm cheating a bit by making you input the numbers into the program itself. (It's somewhat justifiable because quite a few maps, like Lorgon111's Minecraft Bingo, require you to copy and paste commands into chat in order to input a number.)

Thank you abrightmoore for the Block Labels MCEdit filter.

a

scoreboard objectives add a dummy
scoreboard players set m a 6
scoreboard players set n a 8
scoreboard players operation r a += m a
scoreboard players operation r a += n a
tellraw @a {"score":{"name":"r","objective":"a"}}

Non-competing due to difficulties in input, and I have no idea how to count bytes in this thing (the blytes system is flawed for command blocks).

  • 3
    This is by far the best one. Amazing. – Mendeleev Jul 3 '16 at 1:13
  • I don't think that hardcoding the inputs is valid, but I don't know enough about command blocks in Minecraft to be able to judge if there's a way to take input other than hardcoding. Perhaps one of our resident Minecraft experts could weigh in. – Mego Jul 4 '16 at 2:13
  • 2
    Yeah, there's zero text input in MC, besides "please copy and paste this command". A number keypad is possible with a /tellraw, but will be barely usable all golfed, not to mention 500kb thanks to /tellraw's obscenely strict syntax. I guess an alternative would be for it to count something in-world, like pigs+cows, or red wool+blue wool. – quat Jul 4 '16 at 5:51
  • 1
    @quat As we're usually using hopper to count things in minecraft, I guesse it would be the way to go. An other way to deal with this would be doable in pure redstone too by using levers. As we don't have any restriction, and the bit is the biggest natural value reachable in minecraft, that would result in simply adding two bits with an output of two bits (possibility : 0,1,2. An other solution would be to take in 2 bytes and output on 9 wire, but would be much less golfy. – Katenkyo Jul 4 '16 at 7:08
  • 1

Binary lambda calculus, 4.125 bytes

Input and output as Church numerals.

00000000 01011111 01100101 11101101 0

In lambda calculus, it is λm. λn. λf. λx. m f (n f x).

De Bruijn index: λ λ λ λ 4 2 (3 2 1)


Lambda calculus is a concise way of describing a mapping (function).

For example, this task can be written as λx. λy. x + y

The thing to note is, that this is not a lambda (function) which takes two arguments. This is actually a nested lambda. However, it behaves like a lambda which takes two arguments, so it can be informally described as such. Every lambda formally only takes one argument.

For example, if we apply this lambda to 3 and 4:

x. λy. x + y) 3 4 ≡ (λy. 3 + y) 4 ≡ 3 + 4 = 7

So, the first lambda actually returns another lambda.


Church numerals is a way of doing away with the extra signs, leaving with only lambda symbols and variables.

Each number in the Church system is actually a lambda that specifies how many times the function is applied to an item.

Let the function be f and the item be x.

So, the number 1 would correspond to λf. λx. f x, which means apply f to x exactly once.

The number 3, for example, would be λf. λx. f (f (f x)), which means apply f to x exactly three times.


Therefore, to add two Church numerals (say, m and n) together, it is the same as applying f to x, m + n times.

We can observe that this is the same as first applying f to x, n times, and then applying f to the resulting item m times.

For example, 2 would mean f(f(x)) and 3 would mean f(f(f(x))), so 2 + 3 would be f(f(f(f(f(x))))).

To apply f to x, n times, we have n f x.

You can view m and n as functions taking two arguments, informally.

Then, we apply f again to this resulting item, m times: m f (n f x).

Then, we add back the boilerplate to obtain λm. λn. λf. λx. m f (n f x).


Now, we have to convert it to De Bruijn index.

Firstly, we count the "relative distance" between each variable to the lambda declaration. For example, the m would have a distance of 4, because it is declared 4 lambdas "ago". Similarly, the n would have a distance of 3, the f would have a distance of 2, and the x would have a distance of 1.

So, we write it as this intermediate form: λm. λn. λf. λx. 4 2 (3 2 1)

Then, we remove the variable declarations, leaving us with: λ λ λ λ 4 2 (3 2 1)


Now, we convert it to binary lambda calculus.

The rules are:

  • λ becomes 00.
  • m n (grouping) becomes 01 m n.
  • numbers i becomes 1 i times + 0, for example 4 becomes 11110.

λ λ λ λ 4 2 (3 2 1)

≡ λ λ λ λ 11110 110 (1110 110 10)

≡ λ λ λ λ 11110 110 0101 111011010

≡ λ λ λ λ 0101 111101100101111011010

00 00 00 00 0101 111101100101 111011010

000000000101111101100101111011010

  • 16
    I would like to see the 4.125 byte source file that you pass to the interpreter/compiler. – Martin Ender Jul 2 '16 at 6:41
  • 7
    @MartinEnder Say that to every answer here. – Leaky Nun Jul 2 '16 at 7:09
  • 4
    I would like to see a 0.875 byte solution please. – Mr Lister Jul 3 '16 at 9:42
  • 2
    By meta consensus, unless you can store the program as a file with a fractional amount of bytes, you have to round up. – Pavel Jan 24 '17 at 16:11

Common Lisp, 15 bytes

(+(read)(read))
  • 1
    Welcome to Programming Puzzles & Code Golf! – Dennis Jul 3 '16 at 1:06
  • I'm relatively unfamiliar with CLisp, but would it be possible to remove the spaces? (+(read)(read)) – Mego Jul 3 '16 at 1:39
  • @Mego You're right, it is possible. I didn't know that because I'm also new to Common Lisp, thanks for the info! I edited the source – Byeonggon Lee Jul 3 '16 at 2:57
  • 2
    I guess we both learned something here! Welcome aboard to PPCG! – Mego Jul 3 '16 at 3:20

Stack Cats, 8 + 4 = 12 bytes

]_:]_!<X

Run with the -mn flags. Try it online!

Golfing in Stack Cats is highly counterintuitive, so this program above was found with a few days of brute forcing. For comparison, a more intuitive, human-written solution using the *(...)> template is two bytes longer

*(>-_:[:)>

with the -ln flags instead (see the bottom of this post for an explanation).

Explanation

Here's a primer on Stack Cats:

  • Stack Cats is a reversible esoteric language where the mirror of a snippet undoes the effect of the original snippet. Programs must also be mirror images of itself — necessarily, this means that even-length programs are either no-ops or infinite loops, and all non-trivial terminating programs are of odd length (and are essentially a conjugation of the central operator).
  • Since half the program is always implied, one half can be left out with the -m or -l flag. Here the -m flag is used, so the half program above actually expands to ]_:]_!<X>!_[:_[.
  • As its name suggests, Stack Cats is stack-based, with the stacks being bottomless with zeroes (i.e. operations on an otherwise empty stack return 0). Stack Cats actually uses a tape of stacks, e.g. < and > move one stack left and one stack right respectively.
  • Zeroes at the bottom of the stack are swallowed/removed.
  • All input is pushed to an initial input stack, with the first input at the top and an extra -1 below the last input. Output is done at the end, using the contents of the current stack (with an optional -1 at the bottom being ignored). -n denotes numeric I/O.

And here's a trace of the expanded full program, ]_:]_!<X>!_[:_[:

    Initial state (* denotes current stack):
      ... [] [-1 b a]* [] [] ...
]   Move one stack right, taking the top element with you
      ... [] [-1 b] [a]* [] ...
_   Reversible subtraction, performing [x y] -> [x x-y] (uses an implicit zero here)
      ... [] [-1 b] [-a]* [] ...
:   Swap top two
      ... [] [-1 b] [-a 0]* [] ...
]   Move one stack right, taking the top element with you
      ... [] [-1 b] [-a] []* ...
_   Reversible subtraction (0-0, so no-op here)
!   Bit flip top element, x -> -x-1
      ... [] [-1 b] [-a] [-1]* ...
<   Move one stack left
      ... [] [-1 b] [-a]* [-1] ...
X   Swap the stack to the left and right
      ... [] [-1] [-a]* [-1 b] ...
>   Move one stack right
      ... [] [-1] [-a] [-1 b]* ...
!   Bit flip
      ... [] [-1] [-a] [-1 -b-1]* ...
_   Reversible subtraction
      ... [] [-1] [-a] [-1 b]* ...
[   Move one stack left, taking the top element with you
      ... [] [-1] [-a b]* [-1] ...
:   Swap top two
      ... [] [-1] [b -a]* [-1] ...
_   Reversible subtraction
      ... [] [-1] [b a+b]* [-1] ...
[   Move one stack left, taking the top element with you
      ... [] [-1 a+b]* [b] [-1] ...

a+b is then outputted, with the base -1 ignored. Note that the trickiest part about this solution is that the output stack must have a -1 at the bottom, otherwise an output stack of just [-1] would ignore the base -1, and an output stack of [0] would cause the base zero to be swallowed (but an output stack of [2], for example, would output 2 just fine).


Just for fun, here's the full list of related solutions of the same length found (list might not be complete):

]_:]^!<X
]_:]_!<X
]_:]!^<X
]_:!]^<X
[_:[^!>X
[_:[_!>X
[_:[!^>X
[_:![^>X

The *(>-_:[:)> solution is longer, but is more intuitive to write since it uses the *(...)> template. This template expands to <(...)*(...)> when used with the -l flag, which means:

<       Move one stack left
(...)   Loop - enter if the top is positive and exit when the top is next positive again
        Since the stack to the left is initially empty, this is a no-op (top is 0)
*       XOR with 1 - top of stack is now 1
(...)   Another loop, this time actually run
>       Move one stack right

As such, the *(...)> template means that the first loop is skipped but the second is executed. This allows more straightforward programming to take place, since we don't need to worry about the effects of the loop in the other half of the program.

In this case, the inside of the loop is:

>       Move one stack right, to the input stack
-       Negate top, [-1 b a] -> [-1 b -a]
_       Reversible subtraction, [-1 b -a] -> [-1 b a+b]
:       Swap top two, [-1 b a+b] -> [-1 a+b b]
[       Move one stack left, taking top of stack with you (removing the top b)
:       Swap top two, putting the 1 on this stack on top again

The final > in the template then moves us back to the input stack, where a+b is outputted.

Brain-flak, 6 bytes

({}{})

Try it online!

Brain-flak is a really interesting language with two major restrictions on it.

  1. The only valid characters are brackets, i.e. any of these characters:

    (){}[]<>
    
  2. Every single set of brackets must be entirely matched, otherwise the program is invalid.

A set of brackets with nothing between them is called a "nilad". A nilad creates a certain numerical value, and all of these nilads next to each other are added up. A set of brackets with something between them is called a "monad". A monad is a function that takes an numerical argument. So the brackets inside a monad are evaluated, and that is the argument to the monad. Here is a more concrete example.

The () nilad equals 1. So the following brain-flak code:

()()()

Is evaluated to 3. The () monad pushes the value inside of it on the global stack. So the following

(()()())

pushes a 3. The {} nilad pops the value on top of the stack. Since consecutive nilads are always added, a string of {} sums all of the top elements on the stack. So my code is essentially:

push(pop() + pop())

Minecraft 1.10.x, 924 512 bytes

Thanks to @quat for reducing the blytecount by 48 points and the bytecount by 412.

Alright, so, I took some of the ideas from this answer and made a version of my own, except that this one is capable of accepting non-negative input. A version may be found here in structure block format.

group

(new version looks kinda boring tbh)

Similar commands as the other answer:

scoreboard objectives add a dummy
execute @e[type=Pig] ~ ~ ~ scoreboard players add m a 1
execute @e[type=Cow] ~ ~ ~ scoreboard players add n a 1
scoreboard players operation n a += m a
tellraw @a {"score":{"name":"n","objective":"a"}}

To input numbers, spawn in a number of cows and pigs. Cows will represent value "n" and pigs will represent value "m". The command block system will progressively kill the cows and pigs and assign values as necessary.

This answer assumes that you are in a world with no naturally occurring cows or pigs and that the values stored in "n" and "m" are cleared on each run.

  • For negative integers, you could use 2 other kinds of animals as "neganimals" - 5 horses could represent -5, for example. – Mego Jul 6 '16 at 9:32
  • @Mego Then it would be four inputs, not 2. – Addison Crump Jul 6 '16 at 22:52
  • It would still be two inputs - it's the equivalent of using two's complement for negative numbers. Slightly different format, but still one input. At least, that's my two cents. – Mego Jul 7 '16 at 0:07
  • Might be able to save on blocks by using execute @e[type=Pig] ~ ~ ~ scoreboard players add m a 1, so you don't need any form of clock. – quat Jul 7 '16 at 20:57
  • @quat Ooh. Nice. – Addison Crump Jul 7 '16 at 20:58

Retina, 42 bytes

\d+
$*
T`1p`-_` |-1+
+`.\b.

^(-)?.*
$1$.&

Try it online!

Explanation

Adding numbers in unary is the easiest thing in the world, but once you introduce negative numbers, things get fiddly...

\d+
$*

We start by converting the numbers to unary. This is done by matching each number with \d+ and replacing it with $*. This is a Retina-specific substitution feature. The full syntax is count$*character and inserts count copies of character. Both of those can be omitted where count defaults to $& (i.e. the match itself) and character defaults to 1. So for each input n we get n ones, and we still have potential minus signs in there, as well as the space separator. E.g. input 8 -5 gives:

11111111 -11111

Now in order to deal with negative numbers it's easiest to use a separate -1 digit. We'll use - for that purpose.

T`1p`-_` |-1+

This stage does two things. It gets rid of the space, the leading minus signs, and turns the 1s after a minus sign into - themselves. This is done by matching |-1+ (i.e. either a space or a negative number) and performing a transliteration on it. The transliteration goes from 1p to -_, but here, p expands to all printable ASCII characters and _ means delete. So 1s in those matches get turned into -s and minuses and spaces get removed. Our example now looks like this:

11111111-----
+`.\b.

This stage handles the case where there's one positive and one negative number in the input. If so, there will be 1s and -s in the string and we want them to cancel. This is done by matching two characters with a word-boundary between them (since 1s is considered a word character and - isn't), and replacing the match with nothing. The + instructs Retina to do this repeatedly until the string stops changing.

Now we're left with only 1s or only -s.

^(-)?.*
$1$.&

To convert this back to decimal, we match the entire input, but if possible we capture a - into group 1. We write back group 1 (to prepend a - to negative numbers) and then we write back the length of the match with $.& (also a Retina-specific substitution feature).

  • 2
    This is very clever. – Mego Jul 4 '16 at 2:14
  • Now if only there were an easy way to implement range in Retina. I've tried a few times, but the negatives are a pain. – mbomb007 Jul 6 '16 at 18:33
  • It takes over 40 bytes to add two numbers in this language?? – Mendeleev Sep 24 '16 at 2:10
  • 2
    @DmitryKudriavtsev well, Retina has no concept of numbers... – Martin Ender Sep 24 '16 at 7:42
  • @DmitryKudriavtsev, and that's just integers.... – msh210 Oct 31 '16 at 9:15

Dominoes, 38,000 bytes or 37 tiles

This is created in Tabletop Simulator. Here is a video and here is the file. It is a standard half-adder, composed of an and gate for the 2^1 place value and an xor gate for the 2^0 place value.

enter image description here

Details

  • I/O
    • Start - This is included for clarity (not counted towards total) and is what 'calls' or 'executes' the function. Should be 'pressed' after input is given [Yellow].
    • Input A - This is included for clarity (not counted towards total) and is 'pressed' to indicated a 1 and unpressed for 0 [Green].
    • Input B - This is included for clarity (not counted towards total) and is 'pressed' to indicated a 1 and unpressed for 0 [Blue].
    • Output - This is counted towards total. These dominoes declare the sum. The left is 2^1 and the right is 2^0 [Black].
  • Pressing
    • To give input or start the chain, spawn the metal marble
    • Set the lift strength to 100%
    • Lift the marble above the desired domino
    • Drop the marble

Haskell, 3 bytes

(+)

The parentheses are here because it needs to be an prefix function. This is the same as taking a section of the + function, but no arguments are applied. It also works on a wide range of types, such as properly implemented Vectors, Matricies, Complex numbers, Floats, Doubles, Rationals, and of course Integers.

Because this is Haskell, here is how to do it on the type-level. This will be done at compile time instead of run time:

-- This *type* represents Zero
data Zero
-- This *type* represents any other number by saying what number it is a successor to.
-- For example: One is (Succ Zero) and Two is (Succ (Succ Zero))
data Succ a

-- a + b = c, if you have a and b, you can find c, and if you have a and c you can find b (This gives subtraction automatically!)
class Add a b c | a b -> c, a c -> b

-- 0 + n = n 
instance Add Zero n n
-- If (a + b = c) then ((a + 1) + b = (c + 1))
instance (Add a b c) => Add (Succ a) b (Succ c)

Code adapted from Haskell Wiki

  • 2
    fun fact: this is a polyglot with Cheddar :D – Downgoat Jul 17 '16 at 22:15

dc, 2 bytes

+f

Adds top two items on stack (previously taken from stdin), then dumps the stack's contents to stdout.

EDIT: Upon further consideration, it seems there are several ways this might be implemented, depending on the desired I/O behaviour.

+        # adds top two items and pushes on stack
+n       # adds top two and prints it, no newline, popping it from stack
+dn      # ditto, except leaves result on stack
??+      # takes two inputs from stdin before adding, leaving sum on stack

I suppose the most complete form for the sum would be this:

??+p     # takes two inputs, adds, 'peeks'
         #  (prints top value with newline and leaves result on stack)

Wait! Two numbers can be taken on the same line, separated by a space! This gives us:

?+p
  • I can't see how to use the first example +f , dc -e "?+p" works ok here. – Jasen Jan 9 '17 at 21:38
  • 1
    @Jasen The +f version works if you've already put (exactly two) numbers on the stack. I didn't really know whether dc's I/O is supposed to be std(in|out) or the stack. In retrospect, that was the least sensible option to put at the top of the post. :/ – Joe Jan 10 '17 at 6:12
  • the rules say stack is OK so far as I can tell, – Jasen Jan 10 '17 at 7:04

Mathematica, 4 2 bytes

Tr

Crossed out 4 is still regular 4... Tr applied to a one-dimensional list takes the sum of said list's elements.

Shakespeare Programming Language, 155 152 bytes

.
Ajax,.
Ford,.
Act I:.
Scene I:.
[Enter Ajax and Ford]
Ajax:
Listen to thy heart
Ford:
Listen to THY heart!You is sum you and I.Open thy heart
[Exeunt]

Ungolfed:

Summing Two Numbers in Verona.

Romeo, a numerical man.
Juliet, his lover and numerical counterpart.

Act I: In which Italian addition is performed.

Scene I: In which our two young lovers have a short chat.

[Enter Romeo and Juliet]

Romeo:
  Listen to thy heart.

Juliet:
  Listen to THY heart! Thou art the sum of thyself and I. Open thy heart.

[Exeunt]

I'm using drsam94's SPL compiler to compile this. To test:

$ python splc.py sum.spl > sum.c
$ gcc sum.c -o sum.exe
$ echo -e "5\n16" | ./sum
21

Brachylog, 2 bytes

+.

Expects a list with the two numbers as input

Alternatively, if you want the answer to STDOUT:

+w

Cheddar, 3 bytes

(+)

This is a cool feature of Cheddar called "functionized operators". Credit for this idea goes to @CᴏɴᴏʀO'Bʀɪᴇɴ.

Here are more examples of functionized operators:

(+)(1,2) // 3
(/)(6,2) // 3
(-)(5)   // -5

JavaScript (ES6), 9 bytes

a=>b=>a+b
  • I don't think a nested function counts as a two-input function in javascript – proud haskeller Jul 5 '16 at 16:34
  • 3
    @proudhaskeller yes it does – Patrick Roberts Jul 5 '16 at 16:45
  • This one works in C# also. – Grax Oct 12 '16 at 17:59

PHP, 20 bytes

Surprisingly short this time:

<?=array_sum($argv);

Runs from command line, like:

$ php sum.php 1 2
  • Your script also accepts php sum.php 1 2 3 4 5 6 so I'm not 100% sure if that's ok. – timmyRS Oct 6 '16 at 16:43
  • @timmyRS The submission should work for a specific input format – two integers. I don't think it should handle other inputs, too. – insertusernamehere Oct 6 '16 at 17:02
  • What if the source file name starts with a digit? :) – Alex Howansky Oct 12 '16 at 17:57
  • @AlexHowansky Psssssssst – don't tell anybody. ;) This is the quirk, when running from a file. You can still execute it using the -r flag – then it's not a problem anymore. – insertusernamehere Oct 12 '16 at 17:59

Perl 5.10, 8 bytes

The two numbers to add must be on 2 separate lines for this one to work:

say<>+<>

Try this one here.

One with input on the same line (14 + 1 bytes for -a flag)

say$F[0]+$F[1]

Try it here!

One with input on the same line (19 + 1 bytes for -a flag)

map{$s+=$_}@F;say$s

Try this one here.

Another one, by changing the array default separator (19 + 1 bytes for -a flag as well)

$"="+";say eval"@F"

Try this one here!

  • 2
    Hey, another good example (if this will end up being a catalogue challenge) is the method outlined by Dennis in this post: codegolf.stackexchange.com/q/32884 (ab)using the the -p flag. – Dom Hastings Jul 13 '16 at 15:51
  • Instead of say$F[0]+$F[1], say pop()+pop works (tested in Strawberry 5.20.2 with -E) and saves you a byte. – msh210 Oct 31 '16 at 9:11

Fuzzy Octo Guacamole, 1 byte

a

A function that takes inputs from the top of the stack and outputs by pushing to the stack.

Example running in the REPL:

>>> 8 9 :
[8,9]
>>> a :
17

Shakespeare Programming Language (SPL) , 137 135 bytes

Complete program, golfed:

.
A.
B.
Act I
Scene I
[Enter A and B]
A: Listen to your heart!
B: Listen to your heart! You are the sum of me and you. Open your heart! 

And a brief explanation:

----
.                                 <- Title, everything before the first 
                                     full stop is considered as the tittle and treated as a comment
----
A.                                <- Dramatis personae. Here are introduced the characters in the play.
                                     |Characters are treated as variables.   
B.                                <--
----
Act I                             <- Acts and scenes are used to divide a program into smaller
                                     chunks in order to be able to refer to them later.
                                     |
Scene I                           <--
----
[Enter A and B]                   <- Characters on stage in the current scene, which are the              
                                     variables the program will have access to.
----
A: Listen to your heart!          <- Line of code. All of them have the same structure
                                     Variable: code. In this case, the concrete sentence
                                    "Listen to your heart!" reads an input number and stores it
                                     on the character (variable) refered to.
B: Listen to your heart!          <- Same as above 
   You are the sum of me and you. <- Sum the values of itself and the caharacter (variable)
                                     refered to.
   Open your heart!               <- Output the value of the character (value) refered to.

I am not actualy sure this is the shortest it can go. Check the official page for more info.

Edit 1: Removed the : after Act I and Scene I as it seems that everything after the roman numeral is ignored, thus saving 2 bytes.

  • 2
    This is not valid. The characters have to be from Shakespeare's plays and the :s do have to be there. Also, you need a comma after each character's name for a description. – Oliver Ni Oct 13 '16 at 18:19

><>, 7 6 3 bytes

+n;

Online interpreter

Or try it on TIO with the -v flag.

Try it online

  • Since the question lets you define a function, I believe a simple + would be enough : it would pop two numbers from the stack and put the result of their addition back on the stack. The cost of -v could also be avoided, since reading the numbers could have been done beforehand the function invocation. – Aaron Jul 4 '16 at 7:22
  • 1
    @Aaron: True. But as that solution is already posted for several other languages already I'll keep this as a full program. – Emigna Jul 4 '16 at 8:48
  • 1
    I thought the v flag would be a maximum of +1 byte but either way you could use the fishlanguage.com interpreter and your total would be 3 bytes (it doesn't need -v). – redstarcoder Jan 9 '17 at 15:53
  • @redstarcoder: Everyone always specifies the flag as 3 bytes for fish (and 1 byte for all other languages it seems). Not sure why it's different but I assume it is for a valid reason. – Emigna Jan 9 '17 at 20:10
  • Regardless, you don't need the flag if you just use the fishlanguage.com interpreter. Do you have a link to the meta? I haven't seen any ><> program get added bytes for using integers on the initial stack (I've done it too). – redstarcoder Jan 9 '17 at 20:22

MATL, 1 byte

s

Accepts an array of two integers as input and sums them. While the simple program of + also works, that has already been shown for other languages.

Try it Online

Batch, 25 18 16 bytes

@cmd/cset/a%1+%2

Edit: saved 7 9 bytes by using my trick from Alternating Sign Sequence.

PowerShell v2+, 17 bytes

$args-join'+'|iex

Takes input as two separate command-line arguments, which get pre-populated into the special array $args. We form a string with the -join operator by concatenating them together with a + in the middle, then pipe that string to Invoke-Expression (similar to eval).


Thanks to @DarthTwon for reminding me that when dealing with such minimal programs, there are multiple methods of taking input all at the same byte-count.

$args[0]+$args[1]
param($a,$b)$a+$b

PowerShell is nothing if not flexible.

  • 1
    Yeah, I'm just stalking you here :P Alternate answers: $args[0]+$args[1] and param($a,$b)$a+$b – Darth Twon Jul 27 '16 at 15:32

C# - 11 10 bytes

a=>b=>a+b;

Apparently works in ES6 with no semicolon: 10 bytes

(a,b)=>a+b

A lambda expression.

  • Also valid in ES6 – proud haskeller Jul 5 '16 at 16:34
  • You missed the ending ; – aloisdg Jul 10 '16 at 14:16
  • @aloisdg I was unsure whether I should add a semicolon to end it or not :P Edited. – TuukkaX Jul 10 '16 at 14:24
  • @TuukkaX I think we should use it. It feels more valid. :) – aloisdg Jul 10 '16 at 14:40
  • @aloisdg Techinally it is required in this case, so I'll keep it. – TuukkaX Jul 10 '16 at 14:52

Bubblegum, 98 bytes

00000000: 6672 6f6d 206d 6174 6820 696d 706f 7274  from math import
00000010: 2066 6163 746f 7269 616c 2061 7320 4623   factorial as F#
00000020: 0a74 7279 3a6e 3d69 6e74 2869 292d 313b  .try:n=int(i)-1;
00000030: 6f3d 6e2a 2846 286e 2925 2d7e 6e3d 3d6e  o=n*(F(n)%-~n==n
00000040: 290a 6578 6365 7074 3a6f 3d73 756d 286d  ).except:o=sum(m
00000050: 6170 2869 6e74 2c69 2e73 706c 6974 2829  ap(int,i.split()
00000060: 2929                                     ))

Try it online! (Note that the online interpreter takes input in xxd format)

Bubblegum is really good at three things:

  1. Compressing large outputs,

  2. Testing for primality, and

  3. Adding a sequence of numbers.

It's really really really bad at everything else.

Python, 11 3 bytes

sum

int.__add__

A simple special operator.

C, 35 bytes

s(x,y){return y?s(x^y,(x&y)<<1):x;}

What I've done here is defined addition without the use of boolean or arithmetic operators. This recursively makes x the sum bits by 'xor', and y the carry bits by 'and' until there is no carry. Here's the ungolfed version:

int sum(int x,int y){
    if(y==0){
        //anything plus 0 is itself
        return x;
    }
    //if it makes you happier imagine there's an else here
    int sumBits=x^y;
    int carryBits=(x&y)<<1;
    return sum(sumBits,carryBits);
}
  • Why don't you just add directly? – Esolanging Fruit Mar 19 '17 at 19:51
  • I found that to be boring, the fully golfed version is trivial. – Bijan Mar 19 '17 at 21:56
  • "All answers should show some effort towards reaching a better score. For instance, answers to code golf challenges should try to be as short as possible (within the constraints of the chosen language)." (from codegolf.meta.stackexchange.com/a/7073/61384) – Esolanging Fruit Mar 20 '17 at 2:12
  • 2
    Obviously I thought of just adding the numbers, and I did put effort into making it shorter, only under alternate restraints. I think since this is an unconventional question, it deserves an unconventional answer. Following that rule word for word, there would be no reason to ever put up an answer if someone has already put up a shorter one. If you put up your 20 byte python solution and someone already has a 4 byte version up then you're proving that you don't know how to copy and paste. People put up 20 byte solutions, because we value originality. – Bijan Mar 20 '17 at 3:40
  • 1
    It is implied that it is competitive in the language you are choosing. However, having read up on meta, it seems that I cannot claim that your answer is invalid ("An answer may implement any algorithm, even if golfier ones exist"), so I guess I'll drop it. – Esolanging Fruit Mar 20 '17 at 5:00

Wise, 12 bytes (non-competing)

Mistah Figgins has me beat here

[:??:?^?&<]|

I just made this language so I thought I would try the basics.

Try it online

Explanation

[   ...   ]      #Loop until our carry is zero
 :               #Duplicate the top
  ??             #Roll the top two to the bottom
    :            #Duplicate the top
     ?           #Roll to the bottom

At this point we have n m m n on the stack

      ^          #Xor n and m
       ?         #Roll that to the bottom
        &        #And n and m to create the carry over
         <       #Bitshift to the left
           |     #Remove the extra zero with an or
  • 1
    [?~-!-~]| should work, and it is stack clean – MildlyMilquetoast Mar 22 '17 at 4:30
  • @MistahFiggins Nice answer. I like my answer as is because it uses cool bitwise properties do add and yours is sufficiently different so I would recommend making your own answer to the question. – Post Left Garf Hunter Mar 22 '17 at 4:45

Add++, 7 bytes

+?
+?
O

Try it online!

+? adds the input to the accumulator and the O outputs it as a number.

A function is 1 byte longer at

D,f,@@,+
  • Weird, I would've thought a language called Add++ would be at... well... adding :D – Beta Decay Jun 4 '17 at 21:39
  • Right tool for the job – Robert Fraser Aug 6 '17 at 8:55

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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