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

asked Jul 2, 2016 at 0:40
\$\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\$ Commented 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\$ Commented Dec 4, 2016 at 11:56
  • 1
    \$\begingroup\$ @FinW Sure. As long as they don't get interpreted as octal. \$\endgroup\$ Commented Dec 4, 2016 at 20:47

243 Answers 243

1
...
3 4
5
6 7
...
9
2
\$\begingroup\$

Bespoke, 38 bytes

would I total a quantity?yeah
should I

Bespoke is a new esoteric programming language I created near the start of 2025. It's similar to my earlier esolang Poetic, in that word lengths are converted to instructions. This time, however, the instructions are part of a stack-based language, with arbitrary-precision signed integers and loop breaking/continuing and functions and everything!

Here is this program in "pseudocode" (which is able to run as Bespoke code - in fact, it's equivalent to the given code!):

INPUT N
INPUT N
STACKTOP PLUS
OUTPUT N

This should be self-explanatory.

answered Jan 15 at 18:50
\$\endgroup\$
2
\$\begingroup\$

7, 22 characters, 8 bytes

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

Bash, 18 bytes

f(){expr 1ドル + 2ドル;}
answered Jul 2, 2016 at 3:37
\$\endgroup\$
2
  • \$\begingroup\$ Wouldn't this be shorter as a program rather than as a function? \$\endgroup\$ Commented Jul 2, 2016 at 18:46
  • \$\begingroup\$ @Neil Yeah, I'll post that separately. \$\endgroup\$ Commented 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.

answered Jul 4, 2016 at 9:04
\$\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.

answered Jul 4, 2016 at 11:29
\$\endgroup\$
1
\$\begingroup\$

GO, 29 bytes

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

Not that much to say

answered Jul 13, 2016 at 11:10
\$\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!

answered Jul 17, 2016 at 22:24
\$\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 
answered Jul 17, 2016 at 23:50
\$\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
answered Jul 25, 2016 at 11:41
\$\endgroup\$
1
\$\begingroup\$

jq, 3 characters

add

Sample run:

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

On-line test

answered Jul 27, 2016 at 12:00
\$\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 !

answered Oct 7, 2016 at 14:30
\$\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.

answered Oct 20, 2016 at 18:08
\$\endgroup\$
1
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
answered Oct 20, 2016 at 17:21
\$\endgroup\$
11
  • \$\begingroup\$ Edited the answer. \$\endgroup\$ Commented Oct 20, 2016 at 17:37
  • \$\begingroup\$ @manatwork Edited. \$\endgroup\$ Commented Oct 21, 2016 at 11:21
  • \$\begingroup\$ @manatwork What do you mean? \$\endgroup\$ Commented Oct 21, 2016 at 11:24
  • \$\begingroup\$ @manatwork Oh, ok. \$\endgroup\$ Commented Oct 21, 2016 at 11:27
  • \$\begingroup\$ @manatwork Edited. \$\endgroup\$ Commented Oct 21, 2016 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\$
1
  • \$\begingroup\$ Invalid, you did not count the newline nor the spacing. Also, this is code golf, the aim is conciesness, not coolness \$\endgroup\$ Commented Jan 29, 2019 at 7:53
1
\$\begingroup\$

Swift, 1 byte

+

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

answered Oct 31, 2016 at 20:50
\$\endgroup\$
1
\$\begingroup\$

C, 66 bytes

Typical C omissions with regard to declarations, header files, and return statements. This actually works for any number of decimal integers (up to the limitations of one's shell), including none. The program can be invoked with ./a.out 1 2 [...], as an example.

main(c,v,x)char**v;{x=0;while(c-1)x+=atoi(v[--c]);printf("%d",x);}

Or, more legibly:

main(c,v,x) char**v; {
 x=0;
 while(c-1) x+=atoi(v[--c]);
 printf("%d",x);
}
answered Nov 1, 2016 at 0:49
\$\endgroup\$
2
  • \$\begingroup\$ You don't need to have a full program. Just int f(int a,int b){return a+b;} would probably suffice. \$\endgroup\$ Commented Nov 1, 2016 at 2:11
  • \$\begingroup\$ The challenge stated program or function. I make no claims to have the best solution. Additionally, another user has already provided a standalone function, and to produce an identical one would not contribute much. \$\endgroup\$ Commented Nov 1, 2016 at 2:27
1
\$\begingroup\$

QBIC, 6 bytes

::?a+b

It takes two cmd line params as numbers (with two :'s), names them a and b, and adds them while printing (?).

answered Oct 10, 2016 at 15:51
\$\endgroup\$
1
\$\begingroup\$

Euphoria, 64 bytes

Code:

include get.e
print(1,prompt_number("",{})+prompt_number("",{}))
answered Jan 9, 2017 at 14:20
\$\endgroup\$
1
\$\begingroup\$

Whirl, 32 bytes

01100100001100011110001000111100

Try it online!

Explanation

Whirl has two "rings" of operations, one for control and I/O operations and the other for math operations. The 1 command rotates the current operation ring while the 0 command switches direction of the rotation. Two 0s in a row run the current operation and switch to the other ring.

01100 Read an integer from stdin and store it at the memory pointer
100 Load that value into the math ring data storage
00 Read an integer from stdin and store it at the memory pointer
1100 Add the the values under the memory pointer to the math ring data storage
0111100 Set the control ring data storage to 1
0100 Save the math ring data storage to the memory at the memory pointer
0111100 Print the result from the memory at the memory pointer
answered Jan 20, 2017 at 6:14
\$\endgroup\$
1
\$\begingroup\$

V, 2 bytes

À

Try it online!

You can't see it, but after the À there is a control-a character (ASCII 0x01).

This answer is nice because it shows one of the nice things about V: Numeric input is more convenient. Note how one input is an argument and the other is in the "input" field. This is an allowed input method, and it saves bytes because we want to run something n times, in this case the increment command or ctrl-a.

À " Arg1 times:
 <C-a> " Increment the next number found on this line
answered Jan 23, 2017 at 19:54
\$\endgroup\$
1
\$\begingroup\$

SmileBASIC, 13 bytes

INPUT A,B?A+B
answered Jan 24, 2017 at 4:29
\$\endgroup\$
2
  • \$\begingroup\$ "Input: Two decimal integers. These can be given to the code in standard input, as arguments to the program or function, or as a list." Sure your code handles input? \$\endgroup\$ Commented Jan 24, 2017 at 8:43
  • \$\begingroup\$ Ok, I fixed it. \$\endgroup\$ Commented Jan 24, 2017 at 16:19
1
\$\begingroup\$

Python 3, 22 bytes

lambda a,b:a+b

Trivial answer for a kind of trivial question.

answered Dec 24, 2016 at 17:50
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You could golf this to lambda a,b:a+b. Although there's already a 3-byte python solution here. \$\endgroup\$ Commented Dec 24, 2016 at 21:43
1
\$\begingroup\$

Wise, 9 bytes

[?~-!-~]|

Try it Online!

Takes 2 numbers in, A, and B.

 Implicit input
[ .... ] While the top (B) != 0, repeat:
 ? Move B to the bottom
 ~- Add 1 to the top (A)
 ! Move B back to the top
 -~ Subtract 1 from the top (B)
 | Gets rid of the 0 on top by ORing the top 2
 Implicit output

It boils down to "Add 1 to A, B times."

Less cool than the other Wise answer, but also shorter.

answered Mar 22, 2017 at 4:55
\$\endgroup\$
1
\$\begingroup\$
answered Jun 2, 2017 at 20:08
\$\endgroup\$
1
\$\begingroup\$

Triangular, 6 bytes

$.$%+<

Try it online!

Formats into this triangle:

 $
 . $
% + <

Without directionals or no-ops, the above turns into this: $$+%

Triangular uses postfix notation.

  • $ - read input as integer
  • + - add
  • % - print as integer
answered Jun 14, 2017 at 16:18
\$\endgroup\$
1
\$\begingroup\$

,,,, 1 byte

+

Body must be at least 30 characters; you entered 14.

answered Jun 28, 2017 at 19:35
\$\endgroup\$
1
\$\begingroup\$

Commentator, 4 bytes

////

Outputs by char code. If this isn't allowed, a 6 byte solution is

////*/

which outputs by numerical value.

answered Jul 16, 2017 at 21:10
\$\endgroup\$
1
\$\begingroup\$

tcl, 10

expr $a+$b

If you have namespace path tcl::mathop you can do it shorter for every arithmetic operation:

tcl, 7

+ $a $b

test case on: http://rextester.com/live/FLFPTH24568

answered Jan 9, 2017 at 20:55
\$\endgroup\$
1
\$\begingroup\$

Little Man Computer, 23 bytes (source)

INP
STA 6
INP
ADD 6
OUT

With HLT, 27 bytes (source)

INP
STA 6
INP
ADD 6
OUT
HLT

Online Emulator (Flash)

answered Aug 7, 2017 at 2:50
\$\endgroup\$
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.

answered Sep 26, 2017 at 4:02
\$\endgroup\$
0
1
...
3 4
5
6 7
...
9

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.