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

188 Answers 188

1
\$\begingroup\$

Java (JDK 10), 9 bytes

Long::sum

Try it online!

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

\$\endgroup\$
1
\$\begingroup\$

Unnamed, 25 Bytes

Takes 2 numbers from the input area, then adds them together and prints it to the output area.

Try it (paste the code to the leftmost textarea, write the numbers you want to print to the middle textarea in two separate lines, like 5 and 4 in two different lines, and press run)

, # >1 # , # _+.@0.@1 # .

How?

" # " is the command separator. I will explain the others.

,                       /take one input as integer. store it at the current pointer (initially 0)
 >1                     /move the pointer by 1 cell to the right (now is 1)
   ,                    /take one input as integer and store it at the current pointer, now 1
    _                   /assign                                     to cell 1
     +.                 /      the sum of
      @0.@1             /                the numbers at cell 0 and 1
           .            /print the value in the current pointer (which is 1)
\$\endgroup\$
  • \$\begingroup\$ is the language complete / Is it a stable version ? \$\endgroup\$ – Muhammad Salman Jun 3 '18 at 8:56
  • \$\begingroup\$ it is stable except the documentation (I am way too lazy to write the docs) \$\endgroup\$ – Windmill Cookies Jun 3 '18 at 8:58
  • \$\begingroup\$ Then I highly suggest that you have it added to TIO. You can go here. I suggest that you ping Dennis. \$\endgroup\$ – Muhammad Salman Jun 3 '18 at 9:16
  • \$\begingroup\$ no, thanks, I am working on much better languages. I will have them added to tio when I finish them, but not unnamed. unnamed was just like a fun side project of mine, and i was a really bad programmer when I wrote it (I am still very bad, but a little better) \$\endgroup\$ – Windmill Cookies Jun 3 '18 at 9:26
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.

\$\endgroup\$
1
\$\begingroup\$

Burlesque - 4 bytes

ps++

ps   parse
  ++ sum

Try it online.

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

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

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

\$\endgroup\$
  • 1
    \$\begingroup\$ 8, also you have unneeded spaces anyway \$\endgroup\$ – ASCII-only Jan 29 at 7:48
  • \$\begingroup\$ @ASCII-only Thank you a lot for your solution. \$\endgroup\$ – chau giang Jan 29 at 8:00
  • \$\begingroup\$ You forgot to rename the function \$\endgroup\$ – ASCII-only Jan 29 at 8:02
  • 1
    \$\begingroup\$ lol, now it's 27 bytes not 29 \$\endgroup\$ – ASCII-only Jan 29 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 at 8:12
1
\$\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\$
1
\$\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\$
1
\$\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\$
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!

\$\endgroup\$
1
\$\begingroup\$

Cascade, 4 bytes

#&
+

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

Try it online!

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

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

hh+
h   Take input
 h  Take input
  + Get the sum
\$\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

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

hashmap (non-competing)

Non-competing because I had to add a couple of new commands in.

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

Maple, 3 bytes

`+`

Usage:

> `+`(1,2)
  3
\$\endgroup\$
0
\$\begingroup\$

Gema, 13 characters

* *=@add{*;*}

Sample run:

bash-4.3$ gema '* *=@add{*;*}' <<< '5 16'
21
\$\endgroup\$
0
\$\begingroup\$

golflua, 12 characters

\f(a,b)~a+b$

Sample run:

> \f(a,b)~a+b$ 
> w(f(5,16))
21
\$\endgroup\$
0
\$\begingroup\$

MoonScript, 10 characters

(a,b)->a+b

Sample run:

bash-4.3$ .luarocks/moon <(echo 'print ((a,b)->a+b)(5,16)')
21
\$\endgroup\$
0
\$\begingroup\$

SQF, 19

Using the function-as-a-file format:

params["x","y"];x+y

Call as: [X, Y] call NAME_OF_COMPILED_FUNCTION

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

S.I.L.O.S 38

readIO 
a = i
readIO 
a + i
printInt a


For documentation see the repo https://github.com/rjhunjhunwala/S.I.L.O.S Fee free to try this code online!

\$\endgroup\$
  • \$\begingroup\$ Perhaps you meant printInt instead of prinInt \$\endgroup\$ – Leaky Nun Aug 26 '16 at 15:29
  • \$\begingroup\$ How does it work? \$\endgroup\$ – Leaky Nun Aug 26 '16 at 15:39
  • \$\begingroup\$ @LeakyNun whoopsmy bad, fixing now \$\endgroup\$ – Rohan Jhunjhunwala Aug 26 '16 at 16:16
  • \$\begingroup\$ 2 bytes off \$\endgroup\$ – Leaky Nun Aug 26 '16 at 16:20
  • \$\begingroup\$ @LeakyNun thanks, you showed me a feature I didn't even know my language had! I though readIO must have a prompt after it! \$\endgroup\$ – Rohan Jhunjhunwala Aug 26 '16 at 16:21
0
\$\begingroup\$

Batch, 52 Bytes

set/p x=
set/p y=
set/a z=%x%+%y%
echo %z%
pause>nul

This is the lowest byte number you will have while still making the program work. I did the challenge by making a program, not just what the operation was. This method will allow you to input any number and then any other number, including negatives, and the program will output a number.

\$\endgroup\$
  • \$\begingroup\$ Is this a full program? I don't know batch but it looks like the numbers get inputted by editing the program rather than a prompt of some kind \$\endgroup\$ – Blue Jul 6 '16 at 16:32
  • \$\begingroup\$ Hey Nitrate. Welcome to PPCG. A few problems with this post: this is code-golf, which means you need to shorten your code to as short as possible. You don't have to take input like this - you could possibly take it as command line arguments to shorten it. Nice to see you here, m9. \$\endgroup\$ – Addison Crump Jul 6 '16 at 22:44
  • \$\begingroup\$ @muddyfish The /p switch allows you to set a variable equal to a line of input entered by the user. \$\endgroup\$ – Dennis Oct 18 '16 at 15:36
0
\$\begingroup\$

RubyGolf, 15 bytes

p gets.i+gets.i

code is so short it hit the character limit. ugh.

New language created by me, interpreter going up soon. non competing.

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

Y, 5 bytes

{α+β}

Anonymous function returning the sum of it first and second argument.

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

JavaScript, 27 bytes

function s(a,b){return a+b}

I thought this needed a semi-colon after the return statement, but when typing it into the Chrome Console, it works fine without.

\$\endgroup\$
  • \$\begingroup\$ a=>b=>a+b, but then it will be a duplicate \$\endgroup\$ – TuxCrafting Oct 27 '16 at 18:27
  • \$\begingroup\$ Also (a,b)=>a+b is better, but still, duplicate \$\endgroup\$ – Yotam Salmon Oct 30 '16 at 21:27
0
\$\begingroup\$

2 cases:

Pyth, 5 bytes

Input format: n1, n2

code: +hQeQ

Pyth, 1 byte

Input format: n1+n2

code: Q

(But I'm not sure if the second is called "cheating" :-P)

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

Java, 91 bytes

interface M{static void main(String[]a){System.out.print(new Long(a[0])+new Long(a[1]));}}

Usage: java M <num1> <num2>

Tips appreciated.

\$\endgroup\$
  • 1
    \$\begingroup\$ (a,b)->a+b as a lambda expression \$\endgroup\$ – Pavel Jan 9 '17 at 9:23
  • 1
    \$\begingroup\$ @Pavel Or a->b->a+b to save 1 more byte. \$\endgroup\$ – Kevin Cruijssen Sep 26 '17 at 15:07
0
\$\begingroup\$

PHP, 5 bytes

bcadd

PHP has the BC-Math library for arbitrary length integers.
bcadd adds the numbers represented by the two string operands.

A full program would need 21 bytes:

<?=$argv[1]+$argv[2];

alright 20 bytes with array_sum (assuming that the file name does not start with a digit).

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

Carrot, 5 bytes, non-competing

$^F+$

Try it online! (no permalink)

Input numbers are separated by a newline like so:

x
y

$ in c^rrot mode (the code before the first ^) pops the first value from the input array. So now the stack contains x. After that, this value is converted to a number using F. Then we add it with $, the next value in the input array, ie y. Output is implicit, so this outputs x+y.

An alternative at the cost of 1 byte would be:

#^A + 

note the trailing space

# takes all of the input (separated by a space), and converts it to an Array by splitting on s. Then encounter a +, which is given a as its argument, meaning that all the elements of the array will be summed up.

\$\endgroup\$

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.