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

235 Answers 235

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

Intel 8080 machine code, Altair 8800, 22 bytes

This will add two integers of nearly any size (16, 32, 64-bit, etc) using an Intel 8080 8-bit CPU (c. 1974). This is implemented as a full program, running on a MITS Altair 8800.

Code listing and programming instructions:

Step    Switches 0-7    Control Switch  Instruction Comment
1                       RESET
2       00 001 110      DEPOSIT         MVI  C, 2   ; loop counter set to word size
3       00 000 010      DEPOSIT NEXT                ; value is 2
4       00 010 001      "               LXI  D, 16H ; load address of first term into E:D
5       00 010 110      "                           ; at memory address 16H
6       00 000 000      "          
7       00 100 001      "               LXI  H, 18H ; load address of second term into H:L
8       00 011 000      "                           ; memory address 16H + word size = 18H
9       00 000 000      "          
10      10 101 111      "               XRA  A      ; clear accumulator
11      00 011 010      "               LOOP:LDAX D ; load [E:D] into A
12      10 001 110      "               ADC  M      ; add [H:L] + previous carry, to A
13      00 010 010      "               STAX D      ; store result in A to [E:D]
14      00 001 101      "               DCR  C      ; decrement loop counter
15      11 001 010      "               JZ   DONE   ; if counter is zero, end addition
16      00 010 101      "                           ; jump to step 23
17      00 000 000      "       
18      00 010 011      "               INX  D      ; first term next byte
19      00 100 011      "               INX  H      ; second term next byte
20      11 000 011      "               JMP  LOOP   ; restart loop
21      00 001 001      "                           ; jump to step 11
22      00 000 000      "           
23      01 110 110      "               DONE:HLT    ; halt CPU
24      00 001 110      "                           ; Term 1 low byte (14) 
25      00 000 000      "                           ; Term 1 high byte (0)
26      00 001 111      "                           ; Term 2 low byte (15)         
27      00 000 000      "                           ; Term 2 high byte (0)    
31                      RESET                       ; Reset program counter to beginning
32                      RUN
33                      STOP            
34      00 010 110      EXAMINE                     ; low byte of output displayed on D7-D0
35                      EXAMINE NEXT                ; high byte of output displayed on D7-D0

Try it online!

If entered correctly, RAM contents should look like:

0000    0e 02 11 16 00 21 18 00 af 1a 8e 12 0d ca 15 00 
0010    13 23 c3 09 00 76 0e 00 0f 00

I/O:

The above program adds two 16-bit integers, located in memory address 16H and 18H. This could accept larger integers, for example 32-bit integers by changing steps 3 and 8 to values 4 and 20H respectively, and then input would be in 16H and 20H. Numbers are represented in memory as little endian.

Output is displayed on lights D7-D0.

Example: 14 + 15 = 29 = 00 011 101

enter image description here

Example: 1234 + 4321 = 5555 = 00 010 101, 10 110 011

enter image description here

enter image description here

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

SPDT, 1168 bytes

p 0
t 0 1
t 0 2
t 0 3
t 0 4
t 0 5
t 0 6
t 0 7
t 0 8
t 0 9
t 0 10
t 0 11
t 0 12
t 0 13
t 0 14
t 0 15
t 0 16
r 1 0 33 34
r 9 34 33 17
r 1 0 35 36
r 9 18 36 35
r 2 0 40 41
r 10 37 41 40
r 37 0 42 43
r 17 20 43 42
r 2 0 44 45
r 10 45 44 38
r 37 0 46 47
r 17 47 46 39
r 38 0 48 19
r 39 0 48 19
r 3 0 52 53
r 11 49 53 52
r 49 0 54 55
r 19 22 55 54
r 3 0 56 57
r 11 57 56 50
r 49 0 58 59
r 19 59 58 51
r 50 0 60 21
r 51 0 60 21
r 4 0 64 65
r 12 61 65 64
r 61 0 66 67
r 21 24 67 66
r 4 0 68 69
r 12 69 68 62
r 61 0 70 71
r 21 71 70 63
r 62 0 72 23
r 63 0 72 23
r 5 0 76 77
r 13 73 77 76
r 73 0 78 79
r 23 26 79 78
r 5 0 80 81
r 13 81 80 74
r 73 0 82 83
r 23 83 82 75
r 74 0 84 25
r 75 0 84 25
r 6 0 88 89
r 14 85 89 88
r 85 0 90 91
r 25 28 91 90
r 6 0 92 93
r 14 93 92 86
r 85 0 94 95
r 25 95 94 87
r 86 0 96 27
r 87 0 96 27
r 7 0 100 101
r 15 97 101 100
r 97 0 102 103
r 27 30 103 102
r 7 0 104 105
r 15 105 104 98
r 97 0 106 107
r 27 107 106 99
r 98 0 108 29
r 99 0 108 29
r 8 0 112 113
r 16 109 113 112
r 109 0 114 115
r 29 32 115 114
r 8 0 116 117
r 16 117 116 110
r 109 0 118 119
r 29 119 118 111
r 110 0 120 31
r 111 0 120 31
l 18
l 20
l 22
l 24
l 26
l 28
l 30
l 32
l 31

Try it: https://radvylfprograms.com/spdt


SPDT is an esolang I've been wanting to make for a while now. Aside from I/O, it consists entirely of Single Pole Double Throw, or Form C, relays. This answer, which is possibly imperfectly golfed since I used a custom transpiler with macros to generate it, consists of relays arranged into AND, OR, and XOR gates, which are arranged into half adders and full adders, which are then used to make an 8-bit adder. This could be scaled up arbitrarily, at an \$n\log(n)\$ byte count for \$n\$ input bits.

I generated it with the following SPDT-c code, with SPDT-c being a transpiled language I made shortly after that makes it easier to design complex circuits (run it at https://radvylfprograms.com/spdt/c):

t 0 1
t 0 2
t 0 3
t 0 4
t 0 5
t 0 6
t 0 7
t 0 8

t 0 11
t 0 12
t 0 13
t 0 14
t 0 15
t 0 16
t 0 17
t 0 18

add 1 11 c1 21
addc 2 12 c1 c2 22
addc 3 13 c2 c3 23
addc 4 14 c3 c4 24
addc 5 15 c4 c5 25
addc 6 16 c5 c6 26
addc 7 17 c6 c7 27
addc 8 18 c7 29 28

l 21
l 22
l 23
l 24
l 25
l 26
l 27
l 28
l 29

and i i2 o:
    r i 0 - c
    r i2 c - o

or i i2 o:
    r i 0 - o
    r i2 0 - o

xor i i2 o:
    r i 0 1 2
    r i2 o 2 1

add i i2 o1 o2:
    and i i2 o1
    xor i i2 o2

addc i i2 c o1 o2:
    xor i i2 x
    xor x c o2
    and i i2 a
    and x c a2
    or a a2 o1

The transpiler currently lacks any optimizations, and the wire names it generates are numbers, while SPDT technically allows any non-whitespace combination of characters to be used. I didn't change that for this answer, as it's not a particularly interesting optimization, but it will be coming soon.

\$\endgroup\$
5
\$\begingroup\$

Positionally, 33 bytes

 / v


 +  
   ,
      ;

   <  /

Try It Online!

Positionally is a language I made where there are only two commands - space and non-space. The instruction run depends on the position of the IP.

The characters in the above could be any character aside from spaces. Positionally has implicit input, so the + command adds two numbers from input. Then, , prints it, before ; halts the program.

\$\endgroup\$
5
\$\begingroup\$

Objective-Java*#++--Script.NETnotation.sh, 12 bytes.

.cmd.vbs.txt

Try it online!

How it works:

.cmd         # Gets the input and pushes it to the stack
    .vbs     # Adds the top two items on the stack
        .txt # Prints the top item on the stack
\$\endgroup\$
3
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! The link in the header 404s for me, but looks like an interesting language \$\endgroup\$ Jun 27, 2022 at 2:28
  • \$\begingroup\$ @RadvylfPrograms Oops, I forgot to make the repository public. It should be fixed now. \$\endgroup\$
    – aketon
    Jun 28, 2022 at 0:55
  • \$\begingroup\$ Looks like a cool language! Being based on file extensions is an interesting concept. \$\endgroup\$ Jun 28, 2022 at 1:10
5
\$\begingroup\$

in floop, 17 bytes

r+o?+n?-[r-]r[o;]

Try it online!

in floop is a language created by Rydwolf Programs which runs in an infinite loop. It's a true tarpit, and incredibly hard to program in. It also has four variables (n, o, r, s), three of which we use here, and a tape.

  o?+             Take an input into variable o and increment it
                  ? does nothing if all input is consumed
     n?-          Ditto with n, but decrement it
r+                Increment r
        [  ]      If n is nonzero
         r-       Decrement r
                  If n is nonzero, r will be zero, and vice versa
            r[  ] If r is nonzero (n is zero)
              o;  Output o

In other words, this decrements n and increments o until n is zero, then outputs o.

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

05AB1E, 1 byte

Code:

+

Try it online!.

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

MATLAB, 4 bytes

1 byte removed thanks to @LeakyNun

@sum

This is an anonymous function that takes an array and gives the sum. Example use:

>> f = @sum
f = 
    @sum
>> f([3 4])
ans =
     7
\$\endgroup\$
8
  • \$\begingroup\$ What about sum? \$\endgroup\$
    – Leaky Nun
    Jul 2, 2016 at 2:06
  • \$\begingroup\$ @LeakyNun Thanks, good idea! \$\endgroup\$
    – Luis Mendo
    Jul 2, 2016 at 9:56
  • \$\begingroup\$ 43 bytes? xD BTW: I thought we have to have full program or a function, so I'd say only @sum is a valid answer. Or is there another meta consensus? \$\endgroup\$
    – flawr
    Jul 2, 2016 at 18:19
  • \$\begingroup\$ @flawr I think there is, yes. But I couldn't find it \$\endgroup\$
    – Luis Mendo
    Jul 2, 2016 at 18:20
  • 4
    \$\begingroup\$ Wooah, I helped you reduce from 43 to 4 bytes XD \$\endgroup\$
    – flawr
    Jul 3, 2016 at 10:34
4
\$\begingroup\$

GoLScript, 1 byte (non-competiting)

K

Adds the top 2 numbers on the stack. That's it.

Now how to push them on to the stack, I have no clue. I don't think it's possible.. cough @CᴏɴᴏʀO'Bʀɪᴇɴ cough

\$\endgroup\$
2
  • \$\begingroup\$ Explanation soon to be coming. -- Riker Jul 3 '16 \$\endgroup\$
    – MD XF
    Sep 26, 2017 at 4:42
  • \$\begingroup\$ +1 for a Game of Life language. \$\endgroup\$ Sep 27, 2019 at 5:29
4
\$\begingroup\$

C++ – 56 bytes

Should work on all unsigned integer types:

template<typename U>U f(U a,U b){return b?f(++a,--b):a;}

This is multiplication in the same style:

template<typename U>U g(U a,U b){return b>1?f(g(a,--b),a):(b?a:0);}

Finally exponentiation:

template<typename U>U h(U a,U b){return b>1?g(h(a,--b),a):(b?a:1);}
    

To test:

#include <iostream>

template<typename U>U f(U a,U b){return b?f(++a,--b):a;}
template<typename U>U g(U a,U b){return b>1?f(g(a,--b),a):(b?a:0);}
template<typename U>U h(U a,U b){return b>1?g(h(a,--b),a):(b?a:1);}

int main()
{
    std::cout << f(3, 4) << std::endl;
    std::cout << g(3, 4) << std::endl;
    std::cout << h(3, 4) << std::endl;
    return 0;
}

Output:

7
12
81
\$\endgroup\$
2
  • 2
    \$\begingroup\$ Dude, this is code golf. No need for templates, or the needlessly complicated addition, or even using typename instead of class... \$\endgroup\$ Jul 5, 2016 at 16:36
  • 5
    \$\begingroup\$ OP indicated he was "interested to see how it can be implemented". Thought it was an interesting approach to express addition, multiplication and even exponentiation as increment operations. \$\endgroup\$
    – user15259
    Jul 5, 2016 at 17:21
4
\$\begingroup\$

Shakespeare Programming Language (SPL) , 137 135 bytes

Complete program, golfed:

.
A.
B.
Act I
Scene I
[Enter A and B]
A: Listen to your heart!
B: Listen to your heart! You are the sum of me and you. Open your heart! 

And a brief explanation:

----
.                                 <- Title, everything before the first 
                                     full stop is considered as the tittle and treated as a comment
----
A.                                <- Dramatis personae. Here are introduced the characters in the play.
                                     |Characters are treated as variables.   
B.                                <--
----
Act I                             <- Acts and scenes are used to divide a program into smaller
                                     chunks in order to be able to refer to them later.
                                     |
Scene I                           <--
----
[Enter A and B]                   <- Characters on stage in the current scene, which are the              
                                     variables the program will have access to.
----
A: Listen to your heart!          <- Line of code. All of them have the same structure
                                     Variable: code. In this case, the concrete sentence
                                    "Listen to your heart!" reads an input number and stores it
                                     on the character (variable) refered to.
B: Listen to your heart!          <- Same as above 
   You are the sum of me and you. <- Sum the values of itself and the caharacter (variable)
                                     refered to.
   Open your heart!               <- Output the value of the character (value) refered to.

I am not actualy sure this is the shortest it can go. Check the official page for more info.

Edit 1: Removed the : after Act I and Scene I as it seems that everything after the roman numeral is ignored, thus saving 2 bytes.

\$\endgroup\$
2
  • 7
    \$\begingroup\$ This is not valid. The characters have to be from Shakespeare's plays and the :s do have to be there. Also, you need a comma after each character's name for a description. \$\endgroup\$
    – Oliver Ni
    Oct 13, 2016 at 18:19
  • \$\begingroup\$ You should be testing your code on TIO. \$\endgroup\$ Jan 7, 2020 at 14:47
4
\$\begingroup\$

Java, 31 bytes

int A(int b,int B){return b+B;}

Making the above snippet code compilable costs 9 bytes, resulting in a 40-byte program:

class a{int A(int b,int B){return b+B;}}

The "equivalent" monolithic program that can also handle numbers between 231 and 263-1 (inclusive) is 98 bytes long:

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

Java (lambda expression), 11 bytes

(a,b)->a+b;

This is a java.util.function.BinaryOperator<Integer>. It can also be a java.util.function.BinaryOperator<Long> if you have to add larger numbers.

\$\endgroup\$
17
  • 10
    \$\begingroup\$ Not golfing your code as much as possible is anathema to the point of code golf. \$\endgroup\$
    – user45941
    Jul 2, 2016 at 3:35
  • 2
    \$\begingroup\$ No, it's a lambda function. \$\endgroup\$
    – user45941
    Jul 4, 2016 at 2:30
  • 4
    \$\begingroup\$ @dorukayhan The point is, it's a function submission. We allow those. You don't need an enclosing class, and you don't need to worry about the necessary boilerplate for capturing the function. \$\endgroup\$
    – user45941
    Jul 4, 2016 at 3:07
  • 2
    \$\begingroup\$ @dorukayhan If you look closely at the question, it states that standalone functions are allowed. \$\endgroup\$
    – anna328p
    Jul 4, 2016 at 7:58
  • 2
    \$\begingroup\$ It's too bad this got downvoted. This is the shortest java answer I've ever seen. \$\endgroup\$
    – DJMcMayhem
    Jul 17, 2016 at 21:43
4
\$\begingroup\$

Hexagony, 9 bytes

?{?+@/!'/

Embiggened:

   ? { ?
  + @ / !
 ' / . . .
  . . . .
   . . .

Try it online!

Interestingly, this is only 2 bytes shorter than (what I think is) the most basic version, which is:

   ? { ?
  . . . .
 ' + ! @ .
  . . . .
   . . .

This requires 7 commands, of which one (?, which reads a number from STDIN). Now, as 7 is the 2nd centered hexagonal number, it might be able to fit inside a hexagon of side length 2, if you can use a single flow control character and reuse the ?. I've not been able to figure that out yet though :o(

\$\endgroup\$
4
\$\begingroup\$

Brainfuck, 224 bytes

+[-->++++++[-<------>]+>>,----------]<,[<+++++[->-------
-<]+[<<<]>>[-]>[>[-<<<+<[-]+>>>>]>>]<<,]<-<<<[>[->+<]>[-
<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<[-]<<+<<[-
]+>>>>>[-<+>]]]]]]]]]]]<<<<<]>>>[+++++[->++++++++<]>.>>]

Try it online!

Arbitrary precision. Input is taken newline separated, null terminated.

\$\endgroup\$
4
\$\begingroup\$

C# - 11 10 bytes

a=>b=>a+b;

Apparently works in ES6 with no semicolon: 10 bytes

(a,b)=>a+b

A lambda expression.

\$\endgroup\$
9
  • \$\begingroup\$ Also valid in ES6 \$\endgroup\$ Jul 5, 2016 at 16:34
  • \$\begingroup\$ You missed the ending ; \$\endgroup\$
    – aloisdg
    Jul 10, 2016 at 14:16
  • \$\begingroup\$ @aloisdg I was unsure whether I should add a semicolon to end it or not :P Edited. \$\endgroup\$
    – Yytsi
    Jul 10, 2016 at 14:24
  • \$\begingroup\$ @TuukkaX I think we should use it. It feels more valid. :) \$\endgroup\$
    – aloisdg
    Jul 10, 2016 at 14:40
  • \$\begingroup\$ @aloisdg Techinally it is required in this case, so I'll keep it. \$\endgroup\$
    – Yytsi
    Jul 10, 2016 at 14:52
4
\$\begingroup\$

awk, 14 bytes

{print $1+$2}

I am not sure if this is acceptable because the arguments must be passed through a pipe using echo, or through the stdin stream in a file like so:

[user@localhost ~]$ echo '15 6' | awk -E add.awk
21
[user@localhost ~]$ echo '15 6' > numbers
[user@localhost ~]$ awk -E add.awk < numbers 
21

Permissible or not, I am excited to take my first swing at code golf!

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to PPCG! This is perfectly valid! \$\endgroup\$ Oct 27, 2016 at 18:19
  • \$\begingroup\$ Of course is allowed to take input through STDIN. :) The other awk solution works the same way, just using here-string syntax in the sample run. (Some of us are finding it more readable.) BTW, the space after print is not necessary. \$\endgroup\$
    – manatwork
    Oct 27, 2016 at 18:23
4
\$\begingroup\$

Turing Machine Simulator, 342 bytes

0 _ * r 1
0 * * r *
1 _ * r *
1 * * * 2
2 0 _ r *
2 * * * 3
3 _ * l 4
3 * * r *
4 _ * * halt
4 0 9 l *
4 1 0 l 5
4 2 1 l 5
4 3 2 l 5
4 4 3 l 5
4 5 4 l 5
4 6 5 l 5
4 7 6 l 5
4 8 7 l 5
4 9 8 l 5
5 _ * l 6
5 * * l *
6 _ * l *
6 * * * 7
7 _ 1 r 0
7 0 1 r 0
7 1 2 r 0
7 2 3 r 0
7 3 4 r 0
7 4 5 r 0
7 5 6 r 0
7 6 7 r 0
7 7 8 r 0
7 8 9 r 0
7 9 0 l *

Try it!

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.

Ugh...

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Explanation, please? \$\endgroup\$
    – user41805
    Dec 3, 2016 at 12:12
4
\$\begingroup\$

Vim, 5 bytes

DJ@"<C-a>

Note that <C-a> is one byte: 0x01, which is an unprintable character.

Since V is mostly backwards compatible, you can Try it online!

Explanation:

D           " Delete this line. 
            " By default this will save it into the unnamed register (@")
 J          " Get rid of this empty line
  @"        " Run the unnamed register as if it was typed.
            " Since it's a number, it will provide a count to the next command
    <C-a>   " Increment the next number on this line
\$\endgroup\$
4
\$\begingroup\$

Wise, 12 bytes (non-competing)

Mistah Figgins has me beat here

[:??:?^?&<]|

I just made this language so I thought I would try the basics.

Try it online

Explanation

[   ...   ]      #Loop until our carry is zero
 :               #Duplicate the top
  ??             #Roll the top two to the bottom
    :            #Duplicate the top
     ?           #Roll to the bottom

At this point we have n m m n on the stack

      ^          #Xor n and m
       ?         #Roll that to the bottom
        &        #And n and m to create the carry over
         <       #Bitshift to the left
           |     #Remove the extra zero with an or
\$\endgroup\$
2
  • 1
    \$\begingroup\$ [?~-!-~]| should work, and it is stack clean \$\endgroup\$ Mar 22, 2017 at 4:30
  • \$\begingroup\$ @MercyBeaucou Nice answer. I like my answer as is because it uses cool bitwise properties do add and yours is sufficiently different so I would recommend making your own answer to the question. \$\endgroup\$
    – Wheat Wizard
    Mar 22, 2017 at 4:45
4
\$\begingroup\$

Add++, 7 bytes

+?
+?
O

Try it online!

+? adds the input to the accumulator and the O outputs it as a number.

A function is 1 byte longer at

D,f,@@,+
\$\endgroup\$
2
  • \$\begingroup\$ Weird, I would've thought a language called Add++ would be at... well... adding :D \$\endgroup\$
    – Beta Decay
    Jun 4, 2017 at 21:39
  • \$\begingroup\$ Right tool for the job \$\endgroup\$ Aug 6, 2017 at 8:55
4
\$\begingroup\$

R, 3 bytes

"+"

or

sum

"+" can be called as a function like so: "+"(a,b) because the R interpreter will interpret it (with the parentheses) as the primitive addition function .Primitive("+"). Alternatively, sum will add arbitrary arguments. These are both functions.

Try it online!

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

Piet - 5 Codels

I didn't see one in Piet, so I decided to post one.

It's really the code!

Hold on, let me scale that up a bit for you to see.

Codel size 25

The codel size is 25.

I tested this on npiet. When run, the program will ask for a number, then for another, and then print it out. Due to the nature of Piet, it will continue this cycle until you interrupt it.

There are 17 other variants of the same code. Everything is relative in Piet, so changing the start color will change the rest of the colors. Breaking down the code is as follows:

Light Red - Does nothing.

Dark Blue (hue shift 4, darkness shift 2) - Pushes a number from STDIN.

Green (hue shift 4, darkness shift 2) - Pushes a number from STDIN.

Teal (hue shift 1, darkness shift 0) - Pushes the sum of the top two numbers in the stack.

Dark Green (hue shift 5, darkness shift 1) - Writes top of stack to STDOUT as a number.

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

Vyxal s, 0 bytes


Try it Online!

The s flag takes the sum of the top of the stack. Flag abuse FTW!!!

\$\endgroup\$
3
  • \$\begingroup\$ This is practically MGS y'know \$\endgroup\$ Dec 3, 2021 at 3:13
  • \$\begingroup\$ @RedwolfPrograms And? \$\endgroup\$
    – emanresu A
    Dec 3, 2021 at 3:20
  • \$\begingroup\$ Just giving a reason for my downvote \$\endgroup\$ Dec 3, 2021 at 3:22
4
\$\begingroup\$

sed, 275 bytes

s/[1-9]/0&/g
s/[5-9]/4&/g
s/[89]/4&/g
s/[2367]/xx&/g
s/[13579]/x/g
s/4/xxxx/g
s/[1-8]//g
s/$/ /
:a
s/\(.*\)0\(x*\) \(.*\)0\(x*\) /\1 \3 0\2\4/
ta
s/  *//g
:c
s/0xxxxxxxxxx/x0/g
tc
s/0x/-x/g
s/xx/2/g
y/x/1/
s/22/4/g
s/44/8/g
s/81/9/g
s/21/3/g
s/42/6/g
s/43/7/g
s/41/5/g
s/-//g

Takes 2 space-separated non-negative decimal integers on standard input; prints their sum to standard output

Explanation

We represent each input in unary-coded decimal, using x as our digit, and 0 as separator. For example, 42 is written 0xxxx0xx.

#!/bin/sed -f

# Convert to unary decimal
s/[1-9]/0&/g
s/[5-9]/4&/g
s/[89]/4&/g
s/[2367]/xx&/g
s/[13579]/x/g
s/4/xxxx/g
s/[1-8]//g

# Append space to separate second input from output
s/$/ /
# Consume the smallest of each digit from input, and push
# the sum to output
:add
s/\(.*\)0\(x*\) \(.*\)0\(x*\) /\1 \3 0\2\4/
tadd

# Everything is now accumulated in output; remove the spaces
s/  *//g
# Add carry to the next position
:carry
s/0xxxxxxxxxx/x0/g
tcarry

# Back to decimal
s/0x/-x/g
s/xx/2/g
y/x/1/
s/22/4/g
s/44/8/g
s/81/9/g
s/21/3/g
s/42/6/g
s/43/7/g
s/41/5/g
s/-//g

The extension to support decimal fractions is left as an exercise for the reader.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Unfortunately, this doesn't seem to work with negative numbers. \$\endgroup\$
    – Riley
    Oct 10, 2016 at 21:32
  • \$\begingroup\$ Also, if you're okay with using GNU sed, labels can be blank. :;b is an infinite loop. Using -r you don't need the \ in \( and \). And you might be able to get rid of the label :c entirely by jumping to :a everytime, but I'm not sure. \$\endgroup\$
    – Riley
    Oct 10, 2016 at 21:36
  • \$\begingroup\$ @Riley - I overlooked that the numbers might be negative (I was reusing something I already had). I'll have a look at implementing that when I can. As for GNU sed; yes, I do often use the GNU implementation, but for this answer I chose to go the POSIX route. \$\endgroup\$ Oct 11, 2016 at 7:50
3
\$\begingroup\$

Golfscript, 9 2 bytes

~+

~ casts to int[], and + adds.

\$\endgroup\$
4
  • \$\begingroup\$ Just do this. \$\endgroup\$
    – Leaky Nun
    Jul 2, 2016 at 2:23
  • \$\begingroup\$ @LeakyNun Input must be in the form m n not m<newline>n. \$\endgroup\$ Jul 2, 2016 at 2:24
  • \$\begingroup\$ It is the same. \$\endgroup\$
    – Leaky Nun
    Jul 2, 2016 at 2:26
  • \$\begingroup\$ @NoOneIsHere It can be any whitespace character. \$\endgroup\$
    – anna328p
    Jul 2, 2016 at 3:25
3
\$\begingroup\$

Labyrinth, 5 bytes

??+!@

Try it online!

Very straightforward: read input, read input, add, print, terminate.

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

Fishing, 22 bytes

v+CCCCCCCC
  In{In}aP

Explained

Sets casting direction down and casting length to 1.
Read input to the first 2 cells on the tape and convert to numbers.
Add the first 2 cells together and print.

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

Befunge, 5 bytes

&&+.@

  • & takes an integer as input and puts it on the stack
  • + pops two numbers from the stack and puts the sum back on the stack
  • . pops a number from the stack and outputs it as an integer
  • @ ends the program

Try it: http://www.quirkster.com/iano/js/befunge.html

\$\endgroup\$
1
2
3 4 5
8

Your Answer

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

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