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
3 4
5
6 7
1
\$\begingroup\$

Bitwise, 89 bytes

IN 1 &1
IN 2 &1
LABEL &1
AND 1 2 *1
XOR 1 2 *2
SL *1 &1 1
MOV 2 *2 &1
JMP @1 *1
OUT *2 -1

Input and output are raw byte values as that is the only method of I/O for this language. Allowed per this consensus. Try it online!

Ungolfed, written properly, and commented:

IN 1 &1 -1       read a character into r1 if l1 truthy, discarding result
IN 2 &1 -1       read a character into r2
LABEL &1         create label 1 here
AND 1 2 *1       set fr1 to r1 & r2 where & represents bitwise AND
XOR 1 2 *2       set fr2 to r1 ^ r2 where ^ represents bitwise exclusive or
SL *1 &1 1       set r1 to fr1 << 1 where << represents bitwise left shift
MOV 2 *2 &1      move fr2 into r2 if &1 truthy
JMP @1 *1        jump to label 1 if fr1 truthy
OUT *2 &1 -1     print frame register 2 if l1 truthy, discarding result

Note that fr is short for frame register, r is short for register and l is short for literal.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Bash script, 12 bytes

expr $1 + $2

Save as add.sh, then run bash add.sh [argument] [argument].

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ I think this should have been posted as an edit to your previous answer. \$\endgroup\$ – Dennis Jul 2 '16 at 22:10
  • \$\begingroup\$ @Dennis These are somewhat separate: this one has to be run from a file, the other one can be run from the command line. \$\endgroup\$ – anna328p Jul 2 '16 at 22:12
  • 2
    \$\begingroup\$ Yes, I'm aware. I don't think they're different enough to warrant separate answers though. The other does exactly the same; it just wraps the program in a function declaration. \$\endgroup\$ – Dennis Jul 2 '16 at 22:18
  • \$\begingroup\$ @Dennis Okay... \$\endgroup\$ – anna328p Jul 2 '16 at 22:18
1
\$\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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

NotQuiteThere, 8 bytes

0-- 0- 0

Try it online!

Given that one of the aims of this languages was to be unable to perform addition, I think I failed.

How it works

       # Implicit input; 10 and 20
0      # Push 0;   STACK = [10 20 0]
 -     # Subtract; STACK = [10 -20]
  -    # Subtract; STACK = [-30]
   0   # Push 0;   STACK = [-30 0]
    -  # Subtract; STACK = [30]
     0 # Push 0;   STACK = [30 0]
       # Output 30;
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Perl 5, 7 bytes

6 bytes code + 1 for -p.

$_+=<>

Try it online! (-l added for readability.)

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Verbosity, 388 bytes

Include<Input>
Include<Output>
Include<Integer>
Include<MetaFunctions>
Input:DefineVariable<i; 0>
Output:DefineVariable<o; 0>
Integer:DefineVariable<f; Input:ReadEvaluatedLineFromInput<i>>
Integer:DefineVariable<s; Input:ReadEvaluatedLineFromInput<i>>
Integer:DefineVariable<r; Integer:Sum<f; s>>
Output:DisplayAsText<o; r>
DefineMain<> [
MetaFunctions:ExecuteScript<MetaFunctions@FILE>
]

Try it online!

Outputs as Integer<result> (the natural representation of integers in Verbosity)

Ungolfed

Include<Input>
Include<Output>
Include<Integer>
Include<MetaFunctions>

Input:DefineVariable<in; 0>
Output:DefineVariable<out; 0>

Integer:DefineVariable<first; Input:ReadEvaluatedLineFromInput<in>>
Integer:DefineVariable<second; Input:ReadEvaluatedLineFromInput<in>>

Integer:DefineVariable<result; Integer:Sum<first; second>>

Output:DisplayAsText<out; result>

DefineMain<> [
	MetaFunctions:ExecuteScript<MetaFunctions@FILE>
]

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Wumpus, 5 bytes

II+O@

Try it online!

Explanation

Straight-forward and boring:

I   Read the first integer.
I   Read the second integer.
+   Add them.
O   Output the result.
@   Terminate the program.
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Forked, 5 bytes

$$+%&

Try it online!

  • $$ - read two integers
  • + - add top two stack values
  • % - print top of stack as integer
  • & - "terminate", prevents the IP from wrapping
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Momema, 9 bytes

-8+*-8*-8

Try it online!

Momema uses prefix syntax, and assignment statements are implicit (simply writing two expressions ab acts as *a = b;), so this program looks like this:

*(-8) = *(-8) + *(-8)

The cell -8 in Momema is memory-mapped for numeric I/O. Reading from it causes input, and writing to it causes output.

print_num(read_num() + read_num())
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Perl6, 3

Standalone function:

*+*

Complete program (19 bytes):

say [+] slurp.words

| improve this answer | |
\$\endgroup\$
1
+50
\$\begingroup\$

Pain-Flak, 6 bytes

)}{}{(

Try it online!

Pain-Flak is Brain-Flaks evil twin. When translated into regular brain-flak, we get:

({}{})({}{})

The first one is the standard addition snippet. The second one is effectively a NO-OP.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

FRACTRAN, 3 bytes

2/3

Take 2^a*3^b as input, return 2^(a+b).

Try it online!

I'm not sure whether or not extra bytes should be added for input encoding and output decoding.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

6502 machine code - 8 bytes

A5 08 65 09 85 0A 4C 06

Input stored at 0x08 and 0x09, output storad at 0x0A

| improve this answer | |
\$\endgroup\$
1
\$\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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Burlesque - 4 bytes

ps++

ps   parse
  ++ sum

Try it online.

| improve this answer | |
\$\endgroup\$
  • \$\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 '18 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 '18 at 22:10
1
\$\begingroup\$

Aheui (esotope), 15 bytes(5 characters)

방방다망히

Try it online!


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

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Re:direction, 9 characters, 3 bytes

♦►
♦►
◄ ▼

Try it online!

In Re:direction's packed encoding:

F1 F1 B6

(Byte F1 encodes ♦►␤; B6 encodes ◄ ▼).

Explanation

Re:direction is a 2D language that uses a queue of direction commands. At the start of the program, the queue is initialized from user input; an integer n becomes n copies of , then . From that point onwards, whenever we use a direction command, it controls the direction in which the instruction pointer moves but also gets pushed onto the tail of the queue.

The command shifts one direction from that queue, and moves in that direction. So ♦► is effectively a loop that moves any number of from the head of the queue to the tail; as long as the queue starts with , we'll shift it and go right, and hit the in the program, which sends the IP right back where it started (wrapping around the edge of the program) and pushes the to the tail of the queue instead. Once we hit the , it gets deleted from the queue and we move onwards.

We can note that ♦► does not preserve the in the queue. As such, running it twice deletes both from the initial queue, leaving us with a number of equal to the sum of the initial two numbers.

We need to encode the output the same way as the input, meaning that we need to add a and halt the program. A direction command that points to itself will run and then immediately halt the program, so we can use a on a column by itself to do both jobs. We do, however, need to get there; this program uses a to do so (because stray ups and lefts in the queue won't affect the output).

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

RUST, 29 bytes

Save 5 bytes thank to ASCII-only

Try this on line

fn s(a:i32,b:i32)->i32{a+b}

ASCII-only also beat my solution here

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ 8, also you have unneeded spaces anyway \$\endgroup\$ – ASCII-only Jan 29 '19 at 7:48
  • \$\begingroup\$ @ASCII-only Thank you a lot for your solution. \$\endgroup\$ – Chau Giang Jan 29 '19 at 8:00
  • \$\begingroup\$ You forgot to rename the function \$\endgroup\$ – ASCII-only Jan 29 '19 at 8:02
  • 1
    \$\begingroup\$ lol, now it's 27 bytes not 29 \$\endgroup\$ – ASCII-only Jan 29 '19 at 8:10
  • \$\begingroup\$ @ASCII-only, thank you, I just updated it, I count all bytes with my eyes so maybe I was wrong \$\endgroup\$ – Chau Giang Jan 29 '19 at 8:12
1
\$\begingroup\$

Obx, 3 bytes

Obx is an abandoned language created by Phase in 2016.

+xy

With an input of 1 and 2, this program would output 3. Let's learn why.

+xy creates a function that adds x (the first argument) and y (the second argument). The last function created is called with whatever the input is.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Owk, 13 bytes

Owk is an abandoned language created by Phase.

a:λx.λy.x+y

This is written in an unofficial fork(but it's shorter):

a:x+y
| improve this answer | |
\$\endgroup\$
  • 2
    \$\begingroup\$ What do you mean Owk doesn't support input? Don't you have lambdas? A lambda that takes variables as arguments and returns a value counts as valid input/output. Hardcoding two characters into your program is not. \$\endgroup\$ – Value Ink Sep 21 '19 at 3:03
1
\$\begingroup\$

Seed, 11 bytes

4 141745954

Damn, It's quite small

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ This appears to correspond with the program &&+., which loops infinitely outputting zeroes. You need an @ afterwards \$\endgroup\$ – Jo King Jan 7 at 23:45
1
\$\begingroup\$

Re:direction, 9 bytes

▲♦▼
►♦
 ▲

Suprisingly small for a language like this. Re:direction is a language that only uses arrows, a queue, and to go in the direction of the first item on the queue

Explanation

Note: I'll be using .'s to represent instructions I'm not talking about, and I'll split it up into a couple of sections

Input is automatically pushed to the queue as ►'s seperated by ▼'s

▲..
►.      Pushes ▲ into the queue, used as a marker later
 .

...
►♦       Loop that goes through every item of the queue (the input). If its ►, it does nothing to it.
 ▲       If it is ▼, it gets replaced by ▲, which is ignored by the output

.♦▼      If it is an ▲, another ♦ is run, which goes right and removes one item from the queue to make the output correct
.♦       Then, since the ▼ is the only arrow in it's column, it gets pushed to the queue then the program halts
 .

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Cascade, 4 bytes

#&
+

Pretty self explanatory, uses wrapping so there is only 1 input instruction

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

hashmap, 10 bytes

i" "ĥdĐ+

Explanation:

i" "ĥdĐ+
i        Take input
 " "     Push space
    ĥ    Split the input by space
     dĐ  Convert the list to a double then flatten the list
       + Add them together
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Python 3, 14 bytes

lambda x,y:x+y

Pretty self-explanatory lol

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Mornington Crescent, 403 bytes

This challenge is pretty trivial given Mornington Crescent's many functions, but it still clocks in at 403 bytes due to the syntax of the language itself.

Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Parsons Green
Take District Line to Bank
Take Circle Line to Hammersmith
Take District Line to Parsons Green
Take District Line to Parsons Green
Take District Line to Upminster
Take District Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent

The program parses the two numbers from the input string via Parsons Green, adds them in Upminster, and returns the result. This is slightly complicated by the fact that a number must be used to 'reset' Parsons Green after it has been used once so it doesn't overwrite any data.

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

hashmap (Yes, the name starts with a lowercase letter.), 3 bytes

hh+
h   Take input
 h  Take input
  + Get the sum
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

C, 25 Bytes

p(a,b){printf("%d",a+b);}

Usage

p(a,b){printf("%d",a+b);}
main(c,v)char**v;{p(atoi(*++v),atoi(*++v));}

Or, if you want a full program: (+29 chars)

main(c,v)char**v;{printf("%d",atoi(*++v)+atoi(*++v));}

Take 2 arguments and outputs the results in STDOUT

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You dont need to print it, a simple return will suffice. \$\endgroup\$ – Karl Napf Oct 27 '16 at 15:22
0
\$\begingroup\$

Maple, 3 bytes

`+`

Usage:

> `+`(1,2)
  3
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Gema, 13 characters

* *=@add{*;*}

Sample run:

bash-4.3$ gema '* *=@add{*;*}' <<< '5 16'
21
| improve this answer | |
\$\endgroup\$
1
3 4
5
6 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.