50
\$\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\$
  • 28
    \$\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 '16 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 '16 at 11:56
  • 1
    \$\begingroup\$ @FinW Sure. As long as they don't get interpreted as octal. \$\endgroup\$ – anna328p Dec 4 '16 at 20:47

195 Answers 195

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

√ å ı ¥ ® Ï Ø ¿ , 4 bytes

II+o

Fairly basic program, as to be expected.

Explanation

I     › Take input from the command line, evaluate and push to stack
 I    › Take another input
  +   › Add the two together and push to the stack
   o  › Output the top value on the stack
\$\endgroup\$
3
\$\begingroup\$

Microsoft PowerPoint (macro-free), 176 animations, 73 shapes on main slide

(Numbers estimated from XML explorer)

I made a 2-bit adder with carry input and carry output. Numbers represented in binary. Get the PPTX here. Directions are included in the presentation.

I'm thinking this is very golf-able, but it's a fun proof of concept anyway. Obviously, this can be extended to more bits, but frankly, programming in PowerPoint is extremely tedious with its current UI, so I'm going to move on to other things.

How it works

When the presentation starts, it is in input mode. The switches toggle a motion path animation back and forth to indicate 1 or 0.

When the Run button is clicked, it steps through each of the input bits and uses the K-maps for the carry and result bits. If there is a value dependent on the result (such as the carry bit over the second column), it uncovers a button that allows the machine to read that bit. When the final digit is clicked, the machine enters a halt state, displaying the final result in the bottom row.

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

Plumber, 244 176 bytes

  []  []      []
      ][=][]
  []=][][=][
[]=]===]]
][]][=[=]]    =]]
[]][   ][===[=[]
 ]][]=][[[=]=]][][
  []]=]=]=]=[]
  ][]=[]][
  []]=][=][]
= =]=]][[=[==
][=]=]=]=]===][=

Old Design (244 bytes)

  []                []
            [][=[]
 [[=[][]  [][]  ][]][=
][[]  ][[=]]]][]=[[]
[]===][]  ][===][]
][][  []    ][  ]     [][]
      [     ][]=][[[===][[
][]]]=][[]=[=]=]=]]==]=]][
  ][=]=]]==]=][]  ][
    [][=][=[[][[=]][
   ==]=]][[=[= =

I thought I had a good solution for a while...except it didn't work with 0 or 1 as the first input. This program consists of three parts: incrementer, decrementer, and outputter.

The decrementer is on the left, and holds the first value. It is incremented, since a 0 would cause an infinite loop (as the program tries to decrement to 0 and gets a negative value). It will decrement the stored value at execution, and send a packet to the incrementer.

The incrementer is on the right, and stores the second input. When the decrementer sends a packet, it increments its stored value, and sends a packet back to the decrementer.

Whenever the decrementer sends the packet to the incrementer, it is checked by the outputter. If the packet is 0, execution stops and the value of the incrementer is read and outputted. It uses a NOT gate, one of the most complicated parts of the program.

Older design (doesn't work with some inputs), 233 bytes

          []          []
          [][]  [][]  =][]
    []=][]=][[=]][
      [][===][  [][===[]
[][]   [        []    ][][
] [===][=]][     ]
][[=[=[=[=[=]=[]][=[[[][
    ][[=[=[=[==[[=[=][
          []]=][=][]
        = =]=]][[=[== 

The new one is flipped to save bytes, and it's really confusing me. This design is the one I worked with for a week or so when designing the interpreter.

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

Brainetry, 97 bytes

Golfed version:

a b c d e f
a b
a b c d e f
a b c d e f g h
a b c d e

a b c d
a
a b c d e f g h i

a b c d e f g

Does I/O like brainfuck programs, so you input ASCII codepoints and get ASCII characters as output, e.g. inputting two spaces (ASCII 32) the program pints @ (ASCII 64).

To try it online follow this repl.it link, paste the code in the btry/replit.btry file and hit the green "Run" button.

Golfed version was based off of this program:

This Brainetry program is a rather
simple one.
We just need to take two
integers as input from the user (ASCII codepoints)
and then we sum them.

Easier said than done,
right?
Wrong, this one is easy said AND done ;)

Just have to manipulate the inputs wisely.
\$\endgroup\$
2
\$\begingroup\$

Minkolang 0.15, 5 bytes

nn+N.

Try it here.

Explanation

nn       Take two numbers from input
  +      Add
   N.    Output as number and stop.
\$\endgroup\$
2
\$\begingroup\$

Silicon, 3 bytes

II+

Simple enough. Takes input and converts it to an integer twice and adds them together. Output is implicit.

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

Jolf, 1 byte

Interpreter.

u

Take sum of list.

Or, for two bytes, +j, takes two inputs seperated by double newline.

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

R, 13 bytes

scan()+scan()

Will ask twice for an input, and outputs the result of the sum.

Other possibility (18 bytes), using the sum function :

sum(scan(),scan())
\$\endgroup\$
2
\$\begingroup\$

Nim, 3 bytes

`+`

In Nim, the functions behind operators are specified by surrounding them in backticks. This is then the function behind the addition operator, which adds its two parameters.

Use like this:

echo `+`(1, 1)

To test:

$ echo "echo \`+\`(1, 1)" > sum.nim
$ nim c sum.nim
$ ./sum
2
\$\endgroup\$
2
\$\begingroup\$

Sesos, 5 bytes (non-competing)

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\$
  • \$\begingroup\$ I would recommend using jmp instead of nop to make it work for 0-Infinity instead of 1-Infinity. \$\endgroup\$ – Erik the Outgolfer Oct 5 '16 at 16:58
  • \$\begingroup\$ @EriktheGolfer Done. \$\endgroup\$ – acrolith Oct 5 '16 at 22:27
2
\$\begingroup\$

Codelike, 6 bytes

code:

ouuabe

breakdown:

o      changes the direction that the code proceeds in, turning counterclockwise until it hits a command
 uu    takes 2 integers from user input
   a   adds the two integers together and pushes the result to the stack
    b  prints the integer value at the top of the stack
     e ends the program

You can download the compiler here!

(Full disclosure, I did create this language and I did add the b command after reading this challenge but it was something I was already considering adding and it doesn't complete the challenge on its own so I feel that it doesn't violate the rules.)

\$\endgroup\$
  • 2
    \$\begingroup\$ Hi Connor! Welcome to the site. The language you created looks really interesting, well done. As for creating the language and making a change after seeing this problem, we usually allow such answers, but take them out of the running to win the challenge. Noting this fact, like you did, is exactly the right approach. In general, when you have questions like this, chat is a good place to ask. \$\endgroup\$ – isaacg Oct 6 '16 at 5:28
2
\$\begingroup\$

SHENZHEN I/O MCxxxx assembly code, 35 bytes

slx x0
mov x0 acc
add x0
mov acc x0

Take the two numbers via XBus on x0, and send the result on x0

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

SQL, 141 Bytes

Just for fun...

Golfed:

CREATE PROCEDURE S @a INT,@b INT AS BEGIN DELETE FROM ABC INSERT INTO ABC(A)VALUES(@a)INSERT INTO ABC(A)VALUES(@b)SELECT SUM(A)FROM ABC END
GO

Ungolfed:

CREATE PROCEDURE S
@a INT,
@b INT 
AS 
BEGIN 
DELETE FROM ABC 
INSERT INTO ABC(A)
VALUES(@a)
INSERT INTO ABC(A)
VALUES(@b)
SELECT SUM(A)FROM ABC END
GO

Requires a 1 column table creating:

CREATE TABLE ABC
(
A INT,
);

Then call the stored procedure like this:

EXEC S 4, 9
--13
\$\endgroup\$
2
\$\begingroup\$

Ruby, 10 bytes

->a,b{a+b}

An anonymous Proc (I guess, if not a lambda idc) just adds its parameters. Makes use of implicit return in Ruby.

Usage: ->a,b{a+b}[1,2] or ->a,b{a+b}.call(1,2)

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

Japt, 1 byte

x

Here is a non-1 byte solution

U+V

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ I read that as × at first and got really confused :P \$\endgroup\$ – ETHproductions Jan 10 '17 at 20:07
  • \$\begingroup\$ @ETHproductions Ha! It threw me off when you first added ×. I was wondering why it only worked when I copy-pasted it from the docs -- I was typing x :P \$\endgroup\$ – Oliver Jan 10 '17 at 20:20
2
\$\begingroup\$

Kitanai, 15 bytes

add input input

Pretty straightforward :)

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

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

Intcode, 22 bytes

3,0,3,1,1,0,1,2,4,2,99

Fairly basic. IO boilerplate takes up most of the bytecount, given that the language has addition as a builtin (1,0,1,2 would be a valid answer, if snippets were allowed)

\$\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\$
  • \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Martin Ender Apr 12 '18 at 8:37
  • \$\begingroup\$ Thanks. May I ask what you edited ? \$\endgroup\$ – Muhammad Salman Apr 12 '18 at 9:16
  • \$\begingroup\$ Nvm , found that out. Thanks for the edit. :) \$\endgroup\$ – Muhammad Salman Apr 12 '18 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\$

Quantum Circuit 6*Nbits+1 Gates (25 for two 4-bit numbers)

Circuit Diagram

Based on the ripple adder of Cuccaro et al

  • Qubits 0/9 should be left as 0
  • 1:3 represent A in binary
  • 5:8 represent B in binary
  • Answer appears in qubits 5:9

Try it online!

\$\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\$
1
\$\begingroup\$

Bash, 18 bytes

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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