# Add without addition (or any of the 4 basic arithmetic operators)

Problem:

Your goal is to add two input numbers without using any of the following math operators: +,-,*,/.

Additionally, you can't use any built-in functions that are designed to replace those math operators.

Scoring:

Smallest code (in number of bytes) wins.

Update

Most of the programs i've seen either concatenate two arrays containing their numbers, or make first number of a character, append second number characters, then count them all.

Shortest array counter: APL with 8 chars, by Tobia

Shortest array concatenation: Golfscript with 4 chars, by Doorknob

Shortest logarithmic solution: TI-89 Basic with 19 chars, by Quincunx

Integration solution: Mathematica with 45 chars, by Michael Stern

Coolest, in my opinion: bitwise operators in javascript, by dave

• Will it have floats? – Ismael Miguel Feb 16 '14 at 1:06
• Will it have negative numbers? (Currently, all the answers assume that the numbers will be positive, so you probably shouldn't change that) – Doorknob Feb 16 '14 at 3:48
• What about the mathematical solutions? You forgot to list those! This integrates, and this plays with logarithms – Justin Feb 17 '14 at 0:54
• Why did you accept one of the longer solutions? Is it because it accepts negative numbers while the shortest solutions (this and this) don't? If so, my answer supports negative numbers (it also supports floating point) and is shorter than this one. You tagged this question as code-golf, thus you are obliged to accept the shortest solution. – Justin Feb 20 '14 at 21:01
• Define "number". Any integer? Non-negative integers? Do they have to be base-10? – SuperJedi224 Jan 20 '17 at 13:44

# PowerShell, 22 bytes

($args|%{,1*$_}).Count


Try it online!

Where * is an repeat element operator.

## Perl, 23

Since the question does not specify input types and formats, we assume that the input will be natural numbers in the unary number system.

chop($s=<>);print$s.<>


For example, if we are to sum 2 (in base 10) and 3 (in base 10), we input 11 and 111 and we get 11111.

## Python 16 (Using Cheat)

print sum((a,b))


## Python 36 (Using Tricks)

print len("%%0%dd%%0%dd"%(5,7)%(0,0))


## Perl 28

print length('0'x$a.'0'x$b);

• you could save a few bytes with: print length 1x<>.1x<> you might even want to use -E and say to save two more :) – Dom Hastings Feb 16 '14 at 9:55

PHP

This function works recursively for positive interger values for x and y.

function plus($x,$y) {
return $x?ceil(plus(--$x,$y).".1"):$y;
}


The result of

echo plus(3,4);


is

7

• you are using the - operator. – Mhmd Feb 16 '14 at 14:15

# JavaScript [32 bytes]

Array(a).concat(Array(b)).length


This code adds two non-negative variables a and b. Test in any browser console.

• Or more interactive in 54 bytes: p=prompt,alert(Array(+p()).concat(Array(+p())).length). – VisioN Feb 16 '14 at 17:58

# K, 11

{#,/!:'x,y}


Creates two vectors of length x and y (the two inputs), raze into a single list and then get the length.

• You can avoid the need to raze if you use "where"- check out my K solution! – JohnE May 31 '15 at 2:24

### x86 machine code (32 bit): 3 bytes

here provided in hexadecimal form for ease of reading:

8d 04 18


(no, it's not add eax,ebx)

# Assembly (x86),

Taking a shot at this, not sure if it breaks rule 2 set by the question.

First, assume input 1 was loaded into %eax, and input 2 was loaded into %ecx

leal    (%eax, %ecx), %eax


EDIT: apparently the scale defaults to one, so I'll just take that off there.

• Well, it looks like we had the same idea =) – Matteo Italia Feb 17 '14 at 8:36
• @MatteoItalia it's only 2 bytes in x86-16: 8D 00 -> LEA AX, [BX][SI] with input as BX and SI, output is AX. – 640KB Dec 11 '19 at 19:12

# Maxima, 12

[a,b].[1,1];


I just made use of the dot operator to multiply matrices. In this case I get the inner product of the vectors (a,b) and (1,1) which is of course a+b.

Excel - 31

(presuming numbers in cells A1 and A2)

=LEN(REPT("X",A1)&REPT("X",A2))


The digital equivalent of counting on fingers. :)

# Prolog (SWI), 49 bytes

s(0,Y,Y).
s(X,Y,S):-succ(W,X),s(W,Y,R),succ(R,S).


Defines a predicate s that takes in the two numbers and unifies the result with its third argument (which is the standard way of "returning" a value in Prolog). On Linux, put the code in a file and pass it to swipl -qs; then enter queries at the prompt. Sample run:

dlosc@dlosc:~/golf$swipl -qs addWithoutAdding.prolog ?- s(3,5,X). X = 8 . ?- s(14,42,X). X = 56 .  This actually seems like a fairly Prolog-ish way to do addition--the language does have arithmetic operations, but they've always felt bolted-on to me. • If the first argument is 0, unify the result with the second argument. • Otherwise, let W be the predecessor of X (the succ predicate can go either direction), let R be the result of adding W and Y, and let S be the successor of R. Because of how succ works, only nonnegative integers are supported. # Python 3, 46 Bytes def s(a,b): for i in range(b):a=-~a return a  # SmileBASIC, 55 bytes INPUT A,B SPSET.,0SPROT.,A SPANIM.,12,1,B WAIT?SPROT(0)  Doesn't use any mathematical or string functions Explained: INPUT A,B 'input SPSET 0,0 'create sprite 0 with definition 0 SPROT 0,A 'set the angle of sprite 0 to A degrees SPANIM 0,"R+",1,B 'rotate sprite 0 by B degrees relative to its current rotation WAIT 'wait 1 frame so sprite can update PRINT SPROT(0) 'output the angle of sprite 0  # Jelly - 2,4 bytes ‘¡  If we're allowed to increment, then this increments x y times. ,RFL  ,R create a nested list [[1,2,...,x],[1,2...,y]]. FL flatten the list and count the elements to get your number. # PowerShell, 31 bytes param($a,$b)(,1*$a+,1*\$b).Count


Try it online!

The + and * are not arithmetic signs, but array concatenation and element repetition operators respectively. Big thanks to @mazzy for handling 0.

# Python 3, 38 bytes

f=lambda a,b:b and f(a^b,(a&b)<<1)or a


Try it online!

Uses bitwise operations recursively to work out the sum.
Works with some negative numbers (works as long as both are positive, or their sum is less than zero).

# Keg-hr, 10 bytes

(2|(¿|0))!


Try it online!

Places a whole bunch of 0's onto the stack, and then prints the length of the stack. It then uses the hr flag to print the top of the stack raw.

# Javascript - 43, 39, 13 and 4 characters

• The second number must be integer and non-negative.
• The first number can be negative or not an integer.

If the code must take the input and show output, here it is, in 43 characters:

a=prompt,x=a(),y=a();while(y--)x++;alert(x)


But if the code need not take input and output, and just a function that does the sum in needed, then we can do in 39 characters:

function s(x,y){while(y--)x++;return x}


But if you just need an instruction to add two variables x and y (and don't bother in destroying the original value of both), here it is in 13 characters:

while(y--)x++


And, as suggested by @Ismael Miguel (althought he was not exactly suggesting this), by really abusing the rules underspecification, we can note that only +, -, * and / operators were forbidden, but += was not, so it is allowed (it is not a built-in function either, since it is not even a function). This way, we can express the instruction with just 4 characters (and it will always work with negatives and non-integers too for both values):

y+=x

• Those use the + and - operators. y-- is the same as y=y-1 and x++ is the same as x=x+1. – Ismael Miguel Feb 16 '14 at 7:15
• @IsmaelMiguel No, the increment and the decrement are not the same as the adding and subtracting operators. Just because x++ happens to do the same as x=x+1 it does not makes it be a form of the + operator. Ditto for --. – Victor Stafusa Feb 16 '14 at 7:24
• Just read what you said... Then i could just do (function(a,b){return a+=b;})(1,2); cause this is the same as the increment and decrement operator with a defined step. – Ismael Miguel Feb 16 '14 at 7:34
• @IsmaelMiguel See this: ecma-international.org/ecma-262/5.1/#sec-11.3.1 [[... ++ is evaluated as follows ... using the same rules as for the + operator]], this implies that ++ is not the same operator as +. And although you are trying to prove by contradiction, it happens that += is not the same as + either, and thus is allowed (regardless of it being a increment with defined step or not). Reread the question, it just forbid the +,-,*,/ operators, and += and ++ are not within those. – Victor Stafusa Feb 16 '14 at 7:43
• I love it when people are bitching about the rules and are searching for greyzones. It's a sign of missing honor, even when it's just to show the author to correct them, you could simply say him to correct them, instead of writing stupid answers. – Leo Pflug Feb 17 '14 at 12:16
int Ad(int a,int b){while(b){int c=a & b;a=a ^ b;b=c<<1;}return a;}

• This is code-golf, you are supposed to make the code as short as possible, try removing the whitespace, for instance. – mniip Feb 16 '14 at 15:29

Objective-C - Base 1 & Base 10

Actually a fun little project... converted everything to base-1 then just made it a string and took the length. In base one everything is zeros so 5 would be 00000 and 3 would be 000 so I just made two strings of the input in base-one, appended the strings, then printed the length of the string (which converts base 1 to base 10)

Assuming positive integers for inputs *(Note: calculation takes as many seconds as the sum of the integers inputted)

Golf version (644 characters):

int i1=#;int i2=#;NSString *h;BOOL f1;BOOL f2;[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(a1) userInfo:nil repeats:i1];[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(a2) userInfo:nil repeats:i2];[NSTimer scheduledTimerWithTimeInterval:i1 target:self selector:@selector(s1) userInfo:nil repeats:0];[NSTimer scheduledTimerWithTimeInterval:i2 target:self selector:@selector(s2) userInfo:nil repeats:0];-(void)a1{h=[h stringByAppendingString:@"0"];}-(void)a1{h=[h stringByAppendingString:@"0"];}-(void)s1{f1=1;[self p];}-(void)s2{f2=1;[self p];}-(void)p{if((f1)&&(f2)){NSLog(@"%i",h.length);}}


Understandable version (1210 characters):

int input1 = #;//these can be any positive integer
int input2 = #;//these can be any positive integer
NSString *holder = @"";
BOOL finishedAddingFirst = NO;
BOOL finishedAddingSecond = NO;

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(addFirst) userInfo:nil repeats:input1];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(addSecond) userInfo:nil repeats:input2];
[NSTimer scheduledTimerWithTimeInterval:input1 target:self selector:@selector(stopAddingFirst) userInfo:nil repeats:0];
[NSTimer scheduledTimerWithTimeInterval:input2 target:self selector:@selector(stopAddingSecond) userInfo:nil repeats:0];

-(void)addFirst {
holder = [holder stringByAppendingString:@"0"];
}
-(void)addSecond {
holder = [holder stringByAppendingString:@"0"];
}

-(void)stopAddingFirst {
finishedAddingFirst = YES;
[self printFinalAnswer];
}
-(void)stopAddingSecond {
finishedAddingSecond = YES;
[self printFinalAnswer];
}

-(void) printFinalAnswer {
if ((finishedAddingFirst) && (finishedAddingSecond)) {
NSLog(@"Base-One Sum: %@", holder);
int output = (int)[holder length];
NSLog(@"Base-Ten Sum: %i", output);
}
}

• I took this route as well. Converting to base one was pretty fun, but I used * instead of numbers and at the end I counted the number of * to get my number. Just concentrated the strings, and bam! – Sirens Feb 17 '14 at 23:14

# Javascript/JScript 78 76 bytes:

I know this is a long answer, but here is another approach:

function(a,b,c,d,l){c=[],d=[];c[l='length']=a+!!a,d[l]=b+!!b;return(c+d)[l]}

How this works:

It creates 2 arrays with size a+!!a and b+!!b.

I know it has the + in there, but it is 'adding' a Number with a Boolean value.

Basically, it isn't an arithmetic operator anymore!

In the return, it will convert both arrays to string and concatenate them.

To run this, just wrap it in (), add (n1,n2) to the end and you will have the result.

Notice:

It CANNOT handle negative numbers, NaN, Infinity and other non-numeric inputs.

• I liked it. Your answer is no less abusing than mine, since a+!!a is an increment form and you are actually using the + operator, just abusing its semantics of automatic coercing of boolean to number to argue that it is not an arithmetic operator anymore. – Victor Stafusa Feb 16 '14 at 8:46
• Save 6 chars: Instead of _(a,b,c,d,l), use just _(a,b). – Victor Stafusa Feb 16 '14 at 8:48
• I can save 6 chars and have a hole in the function. I prefer to do it "right". And i just noticed now that i can cut 2 chars. And yes, you are right, I'm using the + operator, but it isn't arithmetic. And yes, I'm "abusing" the semantics and internal type casting and all those "goodies" of scripting languages. – Ismael Miguel Feb 16 '14 at 22:13
• “Basically, it isn't an arithmetic operator anymore!” Yeah, it is. Almost unarguably. – Ry- Feb 20 '14 at 1:13
• Not really. It's Number+Boolean. Try writing this in a math test: '0=a*False'. – Ismael Miguel Feb 20 '14 at 1:15

# AutoHotkey - 54 Bytes

This accepts two command line parameters and outputs the result as an error message.

For each command line parameter, it runs a loop with that number and in each iteration, it concatenates one character to a string, then it outputs the length of the string.

It outputs it as an error message because the command to throw an error message is shorter than the commands that show a message box or send something to standard output.

a=a
loop,%1%
b.=a
loop,%2%
b.=a
throw % StrLen(b)

# F# - 36

(String('a',a)+String('b',b)).Length


The + here is not addition, but string concatenation.

# Go [43 bytes]

len(append(make([]int,a),make([]int,b)...))


Perl, 38 chars

for(0..1){push @a,0for(1..<>)}print~~@a


Ruby 49 47

a=gets;b="";gets.to_i.times{b+=".succ"};eval(a+b)

a=gets;b=gets;a.to_i.times{b+=".succ"};eval(b)


## Batch - 71 bytes

For every iteration of a for loop, which will count to each inputted number, this outputs a . to a file named f. It then uses find to count the number of appearances of ..

@(for %%a in (%1 %2)do @for /l %%b in (1,1,%%a)do.)>f 2>e&@find/c"." f


-

h:\MyDocuments\uprof>test.bat 2 4

---------- F: 6


Old Method - 157 bytes

@setLocal enableDelayedExpansion&for /L %%a in (1,1,%1)do @set o=!o!.
@for /L %%b in (1,1,%2)do @set o=!o!.
@set/p"=%o%"<nul>f&for %%c in (f)do @echo %%~zc


This will take two values as input, count up to them, creating a variable that is the length of the two values added, then output that to a file (using set /p trick instead of echo to avoid a carriage return, which would add an extra two bytes), then gets the size of the file in bytes, which will be the sum of the two input values.

H:\uprof>test.bat 2 3
5

H:\uprof>test.bat 25 112
137


# Python (36)

I think I'll switch to this for daily use , it's very efficient.

c=range(a);c.extend(range(b));len(c)


# Python, 118

This uses a binary approach. I didn't really try to golf it as much as I tried to make it interesting; I've already built binary addition in Minecraft in an 8x3x5 space per bit (!!!) and wanted to compare.

r,c="",0
if b>a:a,b=b,a
while a:
a,b,e,d=a>>1,b>>1,a%2,b%2
r=str(e^d^c)+r;c=(c&d)|(c&e)|(d&e)
r=int(str(c)+r,2)


Thanks to @Sp3000 for shaving off about 50 chars and getting it to actually work in the chat ;D