67
\$\begingroup\$

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>

\$\endgroup\$
3
  • 31
    \$\begingroup\$ 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. \$\endgroup\$
    – Dennis
    Jul 2, 2016 at 0:48
  • 2
    \$\begingroup\$ Can the answer take input with preceding zeros as default? e.g. 5 16 is inputted as 005 016 \$\endgroup\$
    – FinW
    Dec 4, 2016 at 11:56
  • 1
    \$\begingroup\$ @FinW Sure. As long as they don't get interpreted as octal. \$\endgroup\$
    – anna328p
    Dec 4, 2016 at 20:47

235 Answers 235

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

PigeonScript, 1 byte

+

Explanation: + pops the last two items from the stack, adds them, and pushes the result to the stack. Since there is nothing on the stack, the user is prompted for input twice. The inputs are pushed, popped, added, pushed, and the program ends, outputting what's on the stack (the result of input1 + input2)

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

Taxi, 418 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:w 1 l 1 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Addition Alley.Go to Addition Alley:e 5 l 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:w 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:e 1 l 1 r.

Try it online!

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

Sinclair ZX80 BASIC (4K ROM)

The usual rules about the ZX80 and its 16 bit signed integer range apply here. Anything out of this range will not add. And because PRINT A+B is too easy, I came up with two solutions:

Method 1 ~64 bytes:

This assumes that you're adding a positive integer to the first number entered:

 1 INPUT A
 2 INPUT B
 3 IF B=0 THEN GO TO 7
 4 FOR B=B/B TO ABS(B)
 5 LET A=A+1
 6 NEXT B
 7 PRINT A

Method 2 ~24 bytes

A much simpler solution, where you are adding two -/+ integers together, simply do this:

 1 INPUT A
 2 INPUT B
 3 PRINT A+B

Both of these listings are likely to work on all variants of 8-bit BASIC, although would not be optimised on most of them.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ There are no such things as functions on a Sinclair ZX80 (as far as I know anyway) so both solutions are complete symbolic listings. \$\endgroup\$ Mar 28, 2017 at 20:55
2
\$\begingroup\$

Cubically, 10 8 bytes

$+7$+7%6

Try it online!

Cubically is a language relatively early in development. Its most unique feature is that its primary memory takes the form of a virtual Rubik's Cube with the colors replaced by numbers from 0 to 5. This Rubik's Cube cannot be written to, and manipulation of it is done only through rotation commands, with only a single "notepad" memory space which supports more traditional manipulation. All operations consist of a non-digit character, followed by any number of digits representing the memory location to use: 0-5 for the face centered on the chosen number, 6 for the notepad, and 7 for the "input buffer".

All that said, this program uses none of the language's unique features and instead does all operations in the notepad and the input buffer which was added today to finally qualify for this challenge since before now there simply was no input. Explanation:

                  Notepad defaults to 0
$               Read an integer from STDIN
 +7             Add the value in [7] (input buffer) to the notepad
   $            Read an integer from STDIN
    +7          Add the value in [7] (input buffer) to the notepad
      %6        Output the value in [6] (notepad) to STDOUT

The language was updated and now allows the $ command to be called without an argument, saving 2 bytes by not including unused characters

Look forward to more Cubically answers as advanced features are added such as looping and branching!

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

INTERCAL, 74 bytes

DO WRITE IN .1
DO WRITE IN .2
DO (1000) NEXT
PLEASE READ OUT .3
DO GIVE UP

Try it online!

INTERCAL is so user-friendly that even something so simple as adding requires a call to the system library in DO (1000) NEXT. I'm working on a more complete answer using only INTERCAL's, uh, "unique", built-in operators.

PLEASE NOTE for those trying this program: INTERCAL takes input in numbers with each digit as an English (or Sanskrit, Basque, Tagalog, Classical Nahuatl, Georgian, or Kwakiutl) word, separated by spaces, so ONE ONE inputs 11, DALAWA LIMA inputs 25, and ZAZPI BAT BI inputs 712. A newline separates different inputs, and because of how the parser works, there must be a trailing space at the end of the last input. Numbers are output as Roman Numerals.

\$\endgroup\$
1
  • \$\begingroup\$ 57 bytes \$\endgroup\$
    – user100411
    Sep 15, 2021 at 3:52
2
\$\begingroup\$

LOLCODE, 75 bytes

HAI 1.3
I HAS A J
GIMMEH J
I HAS A Q
GIMMEH Q
VISIBLE SUM OF J AN Q
KTHXBYE

Try it online!

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

cubix, 6 bytes

OI\@+I

Try it here!

This maps onto a cube with edge length one.

  O
I \ @ +
  I

Much the same as other stack based answers, push input to the stack twice, add, output and terminate.
Operations are

  • I, input number
  • \, reflect down
  • I, input number
  • +, add top two of stack
  • O, output number
  • \, reflect to the right
  • @, terminate

The following will also work

II/@+O

Mapping to

  I
I / @ +
  O
\$\endgroup\$
2
\$\begingroup\$

JavaScript (Node.js), 28 bytes

f=(a,b)=>b?f(a^b,(a&b)<<1):a

Try it online!

Not for winning rather just for fun. Definitely not the shortest but my fav.

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

Java (JDK 10), 9 bytes

Long::sum

Try it online!

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

7, 8 bytes, 22 characters

1717023740344172360303

Try it online!

This program is encoded on disk as (xxd hexdump):

00000000: 3cf0 9f81 c87a 7830                      <....zx0

7 doesn't really support numbers natively, and thus it's hard to define what a number is for the purpose of a function submission. As such, this is a full program, reading from stdin, outputting to stdout (which explains where much of the length comes from).

This program doesn't support negative numbers, because 7 can't input those using numeric I/O (although it can output them). As such, supporting negative numbers would require the use of character input (and a decimal→integer parser), which would make the program much, much more complex.

Explanation

1717023740344172360303
 7 7   7                Stack element separators
1 1 023                 Initial stack
        40344172360303  Initial program (also stored on the stack)
(Implicit: run the initial program, but leave it on the stack)
        4               Swap with blank element between
         0              Escape top stack element, append it to element below

So at this point, we've effectively swapped the program below the 023 element, escaping that element in the process. The 023 is a program in a domain-specific I/O language; and putting the program as the second stack element means that we can discard it (the second stack element is the only one that can be discarded).

          3             Do I/O using top element, discard second element
    0                   Set I/O format: numeric in decimal
     23                 Input via repeating the third stack element

We now have only two stack elements; 1 at the bottom, and the first input in unary just above it (because we repeated the second-last stack element, which was 1, and thus will have a number of 1s).

           4            Swap with blank element between
            4           Swap with blank element between
             172360     Append an escaped representation of "23" to TOS
                   3    Do I/O using top element, discard second element
               23       Input via repeating the third stack element

So now our stack consists of the first input (in unary) directly below the second stack element (in unary).

                    0   Escape top element, appending it to the element below
                     3  Do I/O using top element, and exit

The 3 command exits the program as we're out of stack, but not before it outputs the number we calculated. The number in question will consist of a number of 7s equal to the first number input, followed by a number of 1s equal to the second number input (these are the unescaped and escaped representations of the same command). Numeric I/O treats 1 and 7 as equivalent, and having a value of +1; thus, the unary number gets translated into decimal and output.

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

Burlesque - 4 bytes

ps++

ps   parse
  ++ sum

Try it online.

\$\endgroup\$
2
  • \$\begingroup\$ How does this work? Can you link to an interactive demo and / or provide instructions on how to execute it? \$\endgroup\$
    – Οurous
    Nov 18, 2018 at 21:57
  • 1
    \$\begingroup\$ ps parses the input into a list and ++ computes the sum of a list. I added a link to the online interpreter. \$\endgroup\$
    – mroman
    Nov 18, 2018 at 22:10
2
\$\begingroup\$

Aheui (esotope), 15 bytes(5 characters)

방방다망히

Try it online!


Meet Aheui(아희), A Korean alphabet-based esoteric programming language.

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

Charcoal, 4 2 bytes

I⁺

Try it online!

Explanation

I Cast to string
 ⁺ Add
   (implicit) Input number
   (implicit) Input number
\$\endgroup\$
2
\$\begingroup\$

Clam, 4 bytes

p+rr

Try it online!

Explanation

p               print ...
   +               the sum of ...
       r               the first line of STDIN and ...
       r               the second line of STDIN
\$\endgroup\$
2
\$\begingroup\$

Whitespace, 36 bytes

[S S S N
_Push_0][S N
S _Duplicate][T N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S S S N
_Push_0][S N
S _Duplicate][T N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][T    S S S _Add][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 newlines only).

Explanation:

When a number is read from STDIN it stores it in the heap-address specified at the top of the stack, and then the Retrieve function can be used to get it later on. So to read a number from STDIN you'll need the following sub-steps:

  1. Put a number on the stack:
    • S at the start: Enable Stack Manipulation
    • S: Push what follows as number to the top of the stack
    • S/T: Positive or negative number
    • Some S and/or T followed by a N: Number as binary, where S=0 and T=1.
  2. Duplicate this number:
    • S at the start: Enable Stack Manipulation
    • NS: Duplicate the top value on the stack
  3. Read a number from STDIN, and store it in the heap-address specified at the top of the stack:
    • TN at the start: Enable I/O
    • TT: Read a number, and place it in the heap specified at the top of the stack
  4. Retrieve this number from the heap
    • TT at the start: Enable Heap Access
    • T: Retrieve a value from the heap with the given heap-address at the top of the stack

So here is every step of the full program above:

Command    Explanation              Stack      Heap     STDIN    STDOUT    STDERR

SSSN       Push 0                   [0]        {}                
SNS        Duplicate top (0)        [0,0]      {}                
TNTT       Read STDIN as integer    [0]        {0:-3}   -3        
TTT        Retrieve heap (at 0)     [-3]       {0:-3}                
SSSN       Push 0                   [-3,0]     {0:-3}                
SNS        Duplicate top (0)        [-3,0,0]   {0:-3}                
TNTT       Read STDIN as integer    [-3,0]     {0:5}    5        
TTT        Retrieve heap (at 0)     [-3,5]     {0:5}                
TSSS       Add top two              [2]        {0:5}                
TNST       Print top as integer     []         {0:5}            2
                                                                           Exit with error

Unfortunately the heap-address cannot be negative, otherwise the second SSSN (Push 0) could have been golfed to SNS (duplicate first STDIN input as heap-address).

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

JavaScript (Node.js), 18 bytes

a=>eval(a.join`+`)

Try it online!

Explanation :

a =>                     // lambda function taking array as input
    eval(               // begin eval
        a.join`+`      // joins all elements in `a` with a `+` sign in between
    )                 // end eval (since this is now a string it gets added up)

Alternate :

JavaScript (Node.js), 9 bytes

x=>y=>x+y

Try it online!

Explanation :

x =>                  // lambda taking x as input 1
    y =>              // which returns lambda with input y
        x + y         // which returns sum of x and y

\$\endgroup\$
3
  • \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ Apr 12, 2018 at 8:37
  • \$\begingroup\$ Thanks. May I ask what you edited ? \$\endgroup\$ Apr 12, 2018 at 9:16
  • \$\begingroup\$ Nvm , found that out. Thanks for the edit. :) \$\endgroup\$ Apr 12, 2018 at 9:20
2
\$\begingroup\$

SystemVerilog (HDL) (93 chars)

Here's a pretty simple 8-bit full adder implementation (including input carry for chaining).

module a(input[7:0] a,input[7:0] b,input d,output c,output[8:0] f);
assign f=a+b+d;
endmodule

Inputs: [7:0]a and b, carry bit d.

Outputs: [8:0]f. The top bit can be used as a carry output signal.

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

Help, Wardoq!, 1 byte

A

Try it online!

Note: Due to technical limitations, this interpreter takes code as the first line, and input as every line after.

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

Kotlin, 22 bytes

fun n(a:Int,b:Int)=a+b
\$\endgroup\$
2
\$\begingroup\$

Scratch 3.0 (scratchblocks3 syntax), 23 bytes/7 points

define (x)(y
say((x)+(y
\$\endgroup\$
1
2
\$\begingroup\$

BrainF*ck, 12 Bytes

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

I'm completely new to code golfing, so if I messed something up or did something wrong please let me know.

Here's how it works:

,>,<   - Stores the two inputs into the first and second cells

[->+<] - Decrements the first cell and adds it to the second, 
         repeats until the first cell is 0

>.     - Moves to the second cell and outputs its value

The inputs and outputs are both as ASCII characters (not too sure if this is allowed. I think it is but I could definitely be wrong, so if it is just let me know).

\$\endgroup\$
4
  • \$\begingroup\$ Welcome to Code Golf. Nice first answer! \$\endgroup\$ Mar 9, 2021 at 20:35
  • 2
    \$\begingroup\$ I've edited your answer just to fix some minor mistakes (the pointer is the number indicating the current cell; the cells are what actually store numbers). Also, you can save a byte by not moving back to the first cell after inputting to the second: ,>,[<+>-]>. \$\endgroup\$
    – Makonede
    Apr 16, 2021 at 17:12
  • \$\begingroup\$ @Makonede it's actually ,>,[<+>-]<. (last pointer movement is wrong) \$\endgroup\$
    – hakr14
    Apr 17, 2021 at 18:56
  • \$\begingroup\$ @hakr14 My bad. \$\endgroup\$
    – Makonede
    Apr 17, 2021 at 19:14
2
\$\begingroup\$

Yggdrasil, 4 bytes

+__$

Try it online!

Yggdrasil automatically substitutes 2 characters for different values when turning the source code in a binary tree. % represents a null byte and _ represents a None value. Yggdrasil then traverses the tree and replaces Nones with sequential command line arguments (i.e. the first encountered, depth-first, is the first argument etc.).

This forms the following binary tree for the memory, where ¹ represents the first argument and ² the second:

  +
 / \
¹   ²

We then run the commands linearly, starting with the memory pointer at the + node. We execute +, which adds the left and right nodes of the memory point, setting the root of the program to ¹+². _ then does nothing, and $ outputs the value under the memory pointer as an integer

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

CSS 172 bytes

For every button add 1 and for every input add 1. Might be buggy on some browsers and also not very practical. Make sure your html file has a body and you actually put in buttons and inputs

*{—n: 0;—d: 0;}li{—-n: calc(var(—-n) + 1 )
}button{—-d: calc(var(—-d) + 1 )
}input{—-d:calc(var(—-d) + 1)}body::after{content: calc(var(—-d) + var(—n))}
\$\endgroup\$
2
\$\begingroup\$

dotcomma, 10 bytes

[,.][,.].,

Dotcomma is a language I recently invented, designed to do things in an interesting way with as few instructions as possible. In order to accomplish this, there are two operators (predicatably . and ,) which can do entirely different things depending on context. This answer's explanation will be very introductory. To see some more complicated code, check out the examples in the page linked in the title.

Anything between brackets is a block. Every block has a return value, which is set by the operator before the closing bracket (or 0 if there is none). The basic reason this program functions is because, when one or more blocks (with no operators in between) are followed by a ., the sum of their return values is computed.

In this program, both blocks start with ,. When preceded by the start of a block, a , will take input. Additionally, when followed by the end of a block, it will output the value given to it (from input or another operator). The .s here do pretty much nothing; they take the return values of the ,s and use it as the return value of their respective blocks, which spaces the , from the end of the block and suppresses its output.

The final , simply takes the value computed by the final . and outputs it.

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

Noxan, 3 bytes

+ŊŊ

No implicit input. (yet)

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

Fennel, 23 bytes:

(fn add [x y] (+ x y ))
\$\endgroup\$
2
\$\begingroup\$

Sesos, 5 bytes

0000000: d605ba 8f07                                       .....

Try it online!

set numin
set numout
get
fwd 1
get
jmp
sub 1
rwd 1
add 1
fwd 1
jnz
rwd 1
put
\$\endgroup\$
2
  • \$\begingroup\$ I would recommend using jmp instead of nop to make it work for 0-Infinity instead of 1-Infinity. \$\endgroup\$ Oct 5, 2016 at 16:58
  • \$\begingroup\$ @EriktheGolfer Done. \$\endgroup\$
    – acrolith
    Oct 5, 2016 at 22:27
2
\$\begingroup\$

Ultrarisky, 1 byte

I0{I

Try It Online!

Ultrarisky is a derivative of Risky made by Rydwolf Programs. While risky uses a 4-bit codepage (and thus has 16 commands that fit two to a byte) ultrarisky uses a two-bit codepage, and has 4 commands that fit four to a byte. It's quite hard to program in due to the lack of identity functions.

 0   # Add
I    # One input
  {I # Absolute value of other input
\$\endgroup\$
1
\$\begingroup\$

Bash, 18 bytes

f(){expr $1 + $2;}
\$\endgroup\$
2
  • \$\begingroup\$ Wouldn't this be shorter as a program rather than as a function? \$\endgroup\$
    – Neil
    Jul 2, 2016 at 18:46
  • \$\begingroup\$ @Neil Yeah, I'll post that separately. \$\endgroup\$
    – anna328p
    Jul 2, 2016 at 22:02
1
\$\begingroup\$

Prelude, 4 bytes

??+!

Requires my modified Prelude interpreter which uses decimal I/O.

Like several other answers, this is just read, read, add, write.

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