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

2
\$\begingroup\$

PHP 4.1, 9 bytes

This assumes a standard php.ini file, with short_open_tag=On and register_globals=On (default in PHP 4.1).

<?=$A+$B;

This assumes that you are acessing the file through a webserver (like Apache).
The keys A and B contain the numbers you want to sum.
An example: http://localhost/sum.php?A=5&B=16. (POST, GET, SESSION and COOKIE can be used too).

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

Charcoal, 4 2 bytes

I⁺

Try it online!

Explanation

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

BitCycle, 49 bytes

?Av
?v<>  \Cv
~=B/Av
 ^+  <
+ B\^v /~v
   >  /! <

Try it online!

Made so much more complicated by the signed numbers, otherwise it could just be:

?!
?^

This takes input and outputs as signed unary, though the -U flag is used to translate to decimal.

Explanation:

?Av  From input 1
?v<  And input 2
~=B  Push positive numbers into the top B collector
 ^
+ B  Invert bits of negative numbers and push into the bottom B collector
   >   \   Filter one bit from each collector
  B/Av     And the rest go into the A collector
  +  <     And then back into the B collectors
  B\^      If both positive and negative, then both bits are destroyed
   >   /   Otherwise they reflect off the > and go right of each of the \/
   >   \Cv    Collect the remainder of negative bits in the C collector

              Invert the bits and output
      v /~v   Send one of the 0s to output to represent a negative number
   >   /! <   Positive remainders go straight to output
\$\endgroup\$
2
\$\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\$
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\$ – dkudriavtsev Jul 2 '16 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
\$\begingroup\$

Befunge - 5 Bytes

&&+.@

& - Request int from user and push to stack

+ - Pop top two elements from stack and add and push result

. - Pop value and output as int

@ - End program

Try it here (Although you will have to copy/paste into the text area)

Edit: oops, didn't notice the earlier (identical) befunge answer, I'll leave this here unless I'm told to delete it, not sure of the opinion on that.

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

GO, 29 bytes

func (a,b int)int{return a+b}

Not that much to say

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

Yup, 6 bytes

0*-*-#

Try it online!

Explanation

0*-*-#
0        push 0 to the stack   [0]
 *       place input           [0 a]
  -      subtract              [-a]
   *     place input           [-a b]
    -    subtract              [-a-b]
                             = [b+a]
     #   output

As a function on -cheat mode, 9 bytes:

0~--0~-=+

Try it online!

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

SML, 3 bytes

op+

This is the prefix version of the infix +. If we input it like this in an interpreter (for example Moscow ML), it's type is displayed

- op+;
> val it = fn : int * int -> int

which tells us how to use it: Given a tuple of integers, an integer will be returned.

- op+(17,25);
> val it = 42 : int 
\$\endgroup\$
1
\$\begingroup\$

GAP, 2 Bytes

\+

The backslash is GAP's way to turn an infix operator (and some more, there is also \[\] for indexing) to a function.

Here is an example use:

gap> \+(4,3);
7
\$\endgroup\$
1
\$\begingroup\$

jq, 3 characters

add

Sample run:

bash-4.3$ jq 'add' <<< '[5,16]'
21

On-line test

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

Elixir, 7 bytes

& &1+&2

Anonymous function defined using the capture operator. Another version is &(&1+&2), however this approach saves 1 byte. The verbose version is fn a,b->a+b end - 15 bytes.

Full program with test case (yes, the . in the function call is mandatory!):

s=& &1+&2
IO.puts s.(1,6) #7

Try it online on ElixirPlayground !

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

C, 49 bytes

main(a,b){scanf("%d %d",&a,&b);printf("%d",a+b);}

Can't really do much to golf it down.

For fun:

The following works only if 0 <= sum < 256 (it's 59 bytes long):

a;main(c,v)char**v;{return a++&2?c-3:main(c+atoi(*++v),v);}

Use gcc to compile, and ./a.out [your 2 nums]; echo $? to run it.

Here's the ungolfed version of that program:

/* Global int auto-initialized to 0 */
a;

/* The main method with two int params */
/* 'c' is argc, and 'v' is argv */
main(c, v)

/* Yes, this is valid. It defines 'v' as a char** */
char** v;

{
    /* Checks to see if a == 2, and increments a.
     * I only want recursion to happen twice. */
    if (a++ & 2)
    {
        /* Since "argc" is 3, we need to subtract it from the final answer */
        return c - 3;
    }
    else
    {
        /* Get the next int value of "argv" and add it to 'c'.
         * Then call main() again with the updated value */
        return main(c + atoi(*++v), v);
    }
}

So, main() returns the value of the sum of the two numbers (essentially, I'm forcing it to return a custom exit code). The program won't output the exit code, so calling echo $?, in the same command as running the program, outputs the return value of that program.

The range of exit codes only exist between 0 and 255, so if you run the program trying to sum 255 and 1, it will wrap around and output 0.

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

Ruby, 17 bytes

** Edit: Big thank you to @steenbergh and @TùxCräftîñg for their help **

def c(a,b)a+b end
\$\endgroup\$
  • \$\begingroup\$ Edited the answer. \$\endgroup\$ – BoeNoe Oct 20 '16 at 17:37
  • \$\begingroup\$ @manatwork Edited. \$\endgroup\$ – BoeNoe Oct 21 '16 at 11:21
  • \$\begingroup\$ @manatwork What do you mean? \$\endgroup\$ – BoeNoe Oct 21 '16 at 11:24
  • \$\begingroup\$ @manatwork Oh, ok. \$\endgroup\$ – BoeNoe Oct 21 '16 at 11:27
  • \$\begingroup\$ @manatwork Edited. \$\endgroup\$ – BoeNoe Oct 21 '16 at 11:27
1
\$\begingroup\$

Befunge, 7 bytes

#v&<
 +
 .
 @

Befunge is an esoteric language that can execute in any cardinal direction on a 2 dimensional plane. Executing left to right from the top left (default) we get the following set of operations ((x,y) = coordinates of operation with (0,0) in the top left)

(0,0): skip next cell in execution path (1,0)
(2,0): ask for user input and push it to the stack
(3,0): reverse direction of execution
(2,0): ask for user input and push it to the stack
(1,0): begin executing downward
(1,1): pop first two values on stack, add them and push result
(1,2): pop stack and output value
(1,3): end

&&+.@ would also work, and in only 5 bytes, but is not nearly as cool

\$\endgroup\$
  • \$\begingroup\$ Invalid, you did not count the newline nor the spacing. Also, this is code golf, the aim is conciesness, not coolness \$\endgroup\$ – ASCII-only Jan 29 at 7:53
1
\$\begingroup\$

Swift, 1 byte

+

since operator + is defined as function(public func +(lhs: Int, rhs: Int) -> Int)

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