40
\$\begingroup\$

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

\$\endgroup\$
13
  • 1
    \$\begingroup\$ Will it have floats? \$\endgroup\$ Commented Feb 16, 2014 at 1:06
  • 7
    \$\begingroup\$ Will it have negative numbers? (Currently, all the answers assume that the numbers will be positive, so you probably shouldn't change that) \$\endgroup\$
    – Doorknob
    Commented Feb 16, 2014 at 3:48
  • 4
    \$\begingroup\$ What about the mathematical solutions? You forgot to list those! This integrates, and this plays with logarithms \$\endgroup\$
    – Justin
    Commented Feb 17, 2014 at 0:54
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – Justin
    Commented Feb 20, 2014 at 21:01
  • 3
    \$\begingroup\$ Define "number". Any integer? Non-negative integers? Do they have to be base-10? \$\endgroup\$ Commented Jan 20, 2017 at 13:44

89 Answers 89

2
\$\begingroup\$

PowerShell, 22 bytes

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

Try it online!

Where * is an repeat element operator.

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

Vyxal, 8 6 bytes

ẋ??ẋJL

Try it Online!

I can't get base-1 to work.

-2 thx to lyxal

\$\endgroup\$
1
  • \$\begingroup\$ 6 bytes \$\endgroup\$
    – lyxal
    Commented May 30, 2021 at 4:44
1
\$\begingroup\$

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.

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

Python 16 (Using Cheat)

print sum((a,b))

Python 36 (Using Tricks)

print len("%%0%dd%%0%dd"%(5,7)%(0,0))
\$\endgroup\$
1
\$\begingroup\$

Perl 28

print length('0'x$a.'0'x$b);
\$\endgroup\$
1
  • \$\begingroup\$ you could save a few bytes with: print length 1x<>.1x<> you might even want to use -E and say to save two more :) \$\endgroup\$ Commented Feb 16, 2014 at 9:55
1
\$\begingroup\$

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
\$\endgroup\$
7
  • 2
    \$\begingroup\$ Those use the + and - operators. y-- is the same as y=y-1 and x++ is the same as x=x+1. \$\endgroup\$ Commented Feb 16, 2014 at 7:15
  • \$\begingroup\$ @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 --. \$\endgroup\$ Commented Feb 16, 2014 at 7:24
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Feb 16, 2014 at 7:34
  • \$\begingroup\$ @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. \$\endgroup\$ Commented Feb 16, 2014 at 7:43
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – Leo Pflug
    Commented Feb 17, 2014 at 12:16
1
\$\begingroup\$

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
\$\endgroup\$
1
  • 5
    \$\begingroup\$ you are using the - operator. \$\endgroup\$
    – Mohammad
    Commented Feb 16, 2014 at 14:15
1
\$\begingroup\$

JavaScript [32 bytes]

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

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

\$\endgroup\$
1
  • \$\begingroup\$ Or more interactive in 54 bytes: p=prompt,alert(Array(+p()).concat(Array(+p())).length). \$\endgroup\$
    – VisioN
    Commented Feb 16, 2014 at 17:58
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ You can avoid the need to raze if you use "where"- check out my K solution! \$\endgroup\$
    – JohnE
    Commented May 31, 2015 at 2:24
1
\$\begingroup\$

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)

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

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.

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

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.

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

Excel - 31

(presuming numbers in cells A1 and A2)

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

The digital equivalent of counting on fingers. :)

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

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.

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

Python 3, 46 Bytes

def s(a,b):
 for i in range(b):a=-~a
 return a
\$\endgroup\$
1
\$\begingroup\$

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

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.

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

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.

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

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.

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

Ruby, 41 20 bytes

->a,b{(-a...b).size}

Try it online!

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

MarioLANG, 31 bytes

;
)
;
>[!(
"=#:
  -
) (
!+<
#="

Try it online!

Note: + and - are INCREMENT and DECREMENT respectively, NOT addition and subtraction.

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

Octave, 62 39 37 bytes

@(a,b)fix(toc(tic,pause(a),pause(b)))

Unsigned integers only. Try it online!

-2 thanks to @MarcinKonowalczyk

\$\endgroup\$
1
  • \$\begingroup\$ 37! ^_^ Also, using different method, 36! I really, really like the rounding of the timer though! \$\endgroup\$ Commented Jun 28, 2020 at 16:22
1
\$\begingroup\$

Python 48 47 Bytes

print(len({*range(x)}|{(j,)for j in range(y)})

Does not use +, even as concat. 41 40 without print.

Removed space before for thanks to user8397947.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to the site. You don't need the sapce between ) and for. \$\endgroup\$
    – Wheat Wizard
    Commented Jun 28, 2020 at 20:54
1
\$\begingroup\$

Excel, 29 bytes

=LEN(CONCAT(REPT("x",A1:A2)))

Creates two strings of "x" repeated A1 and A2 times; concatenates the two strings and returns the length of the concatenated string. No built-in sum or sum-like functions.

\$\endgroup\$
0
\$\begingroup\$
int Ad(int a,int b){while(b){int c=a & b;a=a ^ b;b=c<<1;}return a;}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ This is code-golf, you are supposed to make the code as short as possible, try removing the whitespace, for instance. \$\endgroup\$
    – mniip
    Commented Feb 16, 2014 at 15:29
0
\$\begingroup\$

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);
    }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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! \$\endgroup\$
    – Allison
    Commented Feb 17, 2014 at 23:14
0
\$\begingroup\$

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.

\$\endgroup\$
5
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Feb 16, 2014 at 8:46
  • \$\begingroup\$ Save 6 chars: Instead of _(a,b,c,d,l), use just _(a,b). \$\endgroup\$ Commented Feb 16, 2014 at 8:48
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Feb 16, 2014 at 22:13
  • \$\begingroup\$ “Basically, it isn't an arithmetic operator anymore!” Yeah, it is. Almost unarguably. \$\endgroup\$
    – Ry-
    Commented Feb 20, 2014 at 1:13
  • \$\begingroup\$ Not really. It's Number+Boolean. Try writing this in a math test: '0=a*False'. \$\endgroup\$ Commented Feb 20, 2014 at 1:15
0
\$\begingroup\$

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

F# - 36

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

The + here is not addition, but string concatenation.

\$\endgroup\$

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.