Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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

share|improve this question
    
Will it have floats? –  Ismael Miguel Feb 16 at 1:06
    
@IsmaelMiguel - Nope. No floats. –  TheDoctor Feb 16 at 3:09
2  
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 at 3:48
    
@Doorknob the "make two lists, concatenate them, return the length of the resulting list" approach, which many are using, requires positive integers, but other solutions are possible that allow non-integer inputs, negative numbers, or both. –  Michael Stern Feb 16 at 3:55
1  
What about the mathematical solutions? You forgot to list those! This integrates, and this plays with logarithms –  Quincunx Feb 17 at 0:54

55 Answers 55

up vote 2 down vote accepted

Smalltalk, 21 13

All of the following only work on positive integers. See the other Smalltalk answer for a serious one.

version1

shifting to a large integer and asking it for its high bit index (bad, ST indexing is 1-based, so I need an additional right shift):

(((1<<a)<<b)>>1)highBit

version2

similar, and even a bit shorter (due to Smalltalk precedence rules, and no right shift needed):

1<<a<<b log:2 

version3

another variation of the "collection-concatenating-asking size" theme,
given two numbers a and b,

((Array new:a),(Array new:b)) size

using Intervals as collection, we get a more memory friendly version ;-) in 21 chars:

((1to:a),(1to:b))size

not recommended for heavy number crunching, though.

version4

For your amusement, if you want to trade time for memory, try:

Time secondsToRun:[
   Delay waitForSeconds:a.
   Delay waitForSeconds:b.
]

which is usually accurate enough (but no guarantee ;-)))

version5

write to a file and ask it for its size

(
    [
        't' asFilename 
            writingFileDo:[:s |
                a timesRepeat:[ 'x' printOn:s ].
                b timesRepeat:[ 'x' printOn:s ]];
            fileSize 
    ] ensure:[
        't' asFilename delete
    ]
) print
share|improve this answer

Javascript (25)

while(y)x^=y,y=(y&x^y)<<1

This adds two variables x and y, using only bitwise operations, and stores the result in x.

This works with negative numbers, too.

share|improve this answer
1  
@dave, if you're switching to a while, you can save two more chars with while(y)x^=y,y=(y&x^y)<<1! –  Dom Hastings Feb 16 at 16:08
1  
More readable version of the code: Add two numbers without using arithmetic operators. –  Franck Dernoncourt Feb 16 at 16:49
1  
Or as a ECMAScript 6 (recursive) function: f=(x,y)=>y?f(x^y,(x&y)<<1):x It's slightly longer at 28 characters but easier to re-use. –  MT0 Feb 17 at 0:37
2  
@user3125280, The problem isn't "do addition without doing addition" (which is a bit nonsensical), but rather "do addition without basic math operators" –  Brian S Feb 17 at 16:18
4  
@user3125280, I'm sorry, but any rudeness you interpreted from my comment was not intended. I do think you'll have a hard time finding very many people who agree that XOR should be grouped with PLUS in the category of "basic arithmetic," though. Even beyond finding people who agree, the OP explicitly calls out what operators are not permitted, and XOR is not one of them. Ergo, this is a valid answer. –  Brian S Feb 17 at 19:33

C - 38 bytes

main(){return printf("%*c%*c",3,0,4);}

I do cheat a bit here, the OP said to not use any math operators.

The * in the printf() format means that the field width used to print the character is taken from an argument of printf(), in this case, 3 and 4. The return value of printf() is the number of characters printed. So it's printing one ' ' with a field-width of 3, and one with a field-width of 4, makes 3 + 4 characters in total.

The return value is the added numbers in the printf() call.

share|improve this answer
2  
You should make 3 and 4 parameters, and the function doesn't need to be main. Also, if you don't care what you print, you can replace one ' ' with 0 and omit the second. –  ugoren Feb 16 at 8:06

Python - 49 bytes

Assuming input by placement in variables x and y.

from math import*
print log(log((e**e**x)**e**y))

This 61 byte solution is a full program:

from math import*
print log(log((e**e**input())**e**input()))

Considering that you did not ban exponentiation, I had to post this. When you simplify the expression using properties of logarithms, you simply get print input() + input().

This supports both negative and floating point numbers.

Note: I followed gnibbler's advice and split this answer into three. This is the Mathematica solution, and this is the TI-89 Basic solution.

share|improve this answer
    
I was trying to do something similar to that with javascript, but forgot what was the formula since it was some years from last time I saw it and was searching the internet to find it. –  Victor Feb 16 at 7:30
3  
@Victor I created the formula on my own. I remember math very clearly. –  Quincunx Feb 16 at 7:31
1  
Your Mathematica is very close, you just need to capitalize the built-in symbols. Log[Log[(E^E^x)^(E^y)]] works (23 characters, or 22 if you use @ notation for the outer function wrapping). –  Michael Stern Feb 16 at 12:23
    
"If I am allowed to assume input by placement in variables x and y.." I think you can - others do so as well. –  blabla999 Feb 16 at 17:38
    
@MichaelStern: You can save two more characters by skipping the parentheses around E^y. Using Log[Log[(E^E^x)^E^y]] seems to work fine. –  alexwlchan Feb 16 at 17:54

Mathematica, 21 bytes

There are a number of ways to do this in Mathematica. One, use the Accumulate function and toss everything but the final number in the output. As with my other solution below, I assume the input numbers are in the variables a and b. 21 bytes.

Last@Accumulate@{a, b}

More fun, though it is 45 characters, use the numbers to define a line and integrate under it.

Integrate[Fit[{{0, a}, {2, b}}, {x, 1}, x], {x, 0, 2}]

As a bonus, both solutions work for all complex numbers, not just positive integers as seems to be the case for some other solutions here.

share|improve this answer
2  
I love the integration! (although, strictly speaking this adds up something). +1 –  blabla999 Feb 16 at 3:54
    
The 1st solution is invalid. Quoting the author of the challenge: "Additionally, you can't use any built-in functions that are designed to replace those math operators.". I had given this solution: function _(){return array_sum(func_get_args());}. I had to take it down 'cause I couldn't find a short way to "fix" it. –  Ismael Miguel Feb 16 at 22:25
    
@Ismael Miguel Accumulate[] is not designed to replace Plus. It happens to give the sum of a list of numbers among its outputs, and I take advantage of that. –  Michael Stern Feb 16 at 22:28
    
But it does make the sum of all the elements in that list, right? If it does, in my opinion, it's as invalid as using array_sum() in php, which does the same exact thing. –  Ismael Miguel Feb 16 at 22:37
1  
@Ismael Miguel There exists a Mathematica function that sums an array, called Total[]. I agree it would be against the rules as specified to use that function, but I did not do so. The output of Accumulate[{a,b}] is not a+b. –  Michael Stern Feb 16 at 23:52

GolfScript, 6 4 characters/bytes

Input in the form of 10, 5 (=> 15).

~,+,

The + is array concatenation, not addition.

How it works is that , is used to create an array of the length that the number is (0,1,...,n-2,n-1). This is done for both numbers, then the arrays are concatenated. , is used again for a different purpose, to find the length of the resulting array.

Now, here's the trick. I really like this one because it abuses the input format. It looks like it's just inputting an array, but really, since the input is being executed as GolfScript code, the first , is already done for me! (The old 6-character version was ~,\,+, with input format 10 5, which I shaved 2 chars off by eliminating the \, (swap-array)).

Old version (12):

Creates a function f.

{n*\n*+,}:f;

The * and + are string repetition and concatenation respectively, not arithmetic functions.

Explanation: n creates a one-character string (a newline). This is then repeated a times, then the same thing is done with b. The strings are concatenated, and then , is used for string length.

share|improve this answer
    
Does it work for negative numbers too? –  Michael Stern Feb 16 at 3:47
    
@MichaelStern No, but that was never mentioned in the question. Hmm, I've added a comment. Most (in fact, all) of the other answers also assume positives. –  Doorknob Feb 16 at 3:47
    
See my Mathematica solution. In the right language, solutions for negative numbers are possible. –  Michael Stern Feb 16 at 3:53
    
@MichaelStern LOL @ "right language" on this site of all places… –  Tobia Feb 16 at 23:05

C, 29 27 Bytes

Using pointer arithmetic:

f(x,y)char*x;{return&x[y];}

x is defined as a pointer, but the caller should pass an integer.

An anonymous user suggested the following - also 27 bytes, but parameters are integers:

f(x,y){return&x[(char*)y];}
share|improve this answer
    
The first form probably breaks badly if passing two ints on the now-common systems where int has 32 bits, and pointers have 64 bits. The second avoids that problem. –  hvd Feb 17 at 12:24
    
@hvd, Both work, at least on Linux 64bit. Integer parameters are extended to machine register size anyway. –  ugoren Feb 17 at 12:29
    
Ah, fair enough, agreed that that'll likely be the common case. Will comment again if I can find a concrete example that doesn't work, though. :) –  hvd Feb 17 at 12:32

JavaScript [25 bytes]

~eval([1,~x,~y].join(''))
share|improve this answer
    
Your answer looks bad (and downvote-attracting), but it is actually a nice answer. Please delete this one to get rid of the downvotes and repost this with some text explaining it. I will upvote your new answer. –  Victor Feb 18 at 17:36
1  
Now it looks really good, I like it. Certainly is worth more upvotes. –  VisioN Feb 19 at 15:45
if (input1 == 1) && (input2 == 1) {
output = 2
}

if (input1 == 1) && (input2 == 2) {
output = 3
}

if (input1 == 2) && (input2 == 1) {
output = 3
}

if (input1 == 2) && (input2 == 2) {
output = 4
}

... I had infinitely more but it wouldn't let me fit them ALL in here /:

share|improve this answer
11  
Is this code-trolling? –  Mhmd Feb 16 at 7:25
    
Are you aware that this is code-golf? We are supposed to create the shortest solution, not the longest. Save this solution for some other thyme. –  Quincunx Feb 16 at 7:41
1  
@user689 Of course :) But I actually feel kind of sad that the other guy didn't pick up on that.. Haha –  Albert Renshaw Feb 16 at 7:56
2  
@user689 The point of golf is to try and get the highest sc∞re possible right? –  Albert Renshaw Feb 17 at 0:42

J (6)

You didn't say we couldn't use the succ function:

>:@[&0

Usage:

   9>:@[&0(8)
17

It just does 9 repetitions of >: on 8.

The list concatenation approach works, too: #@,&(#&0). And - I know it's against the rules - I can't let this answer go without the most J-ish solution: *&.^ (multiplication under exponentiation).

share|improve this answer

bash, 20 chars

(seq 10;seq 4)|wc -l
share|improve this answer

Brainf*ck, 9 36

,>,[-<+>]

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

This works without using simple addition; it goes through and lays a trail of 1's and then counts them up

Note: The + and - are merely single increments and nothing can be done in brainf*ck without them. They aren't really addition/subtraction so I believe this still counts.

share|improve this answer
    
-1. This is simple addition. If you did something that is not addition, multiplication, etc, then it counts, but as is, this does not count. –  Quincunx Feb 16 at 5:15
    
@Quincunx I fixed it; i did it by goign through and leaving a trail of ones and then sweeping through and 'picking up' that trail –  ASKASK Feb 16 at 5:42
2  
Reversed. Nice job. –  Quincunx Feb 16 at 5:43

Smalltalk (now seriously), 123 118 105(*)

Sorry for answering twice, but consider this a serious answer, while the other one was more like humor. The following is actually executed right at this very moment in all of our machines (in hardware, though). Strange that it came to no one else's mind...

By combining two half-adders, and doing all bits of the words in parallel, we get (inputs a,b; output in s) readable version:

  s := a bitXor: b.            
  c := (a & b)<<1.             

  [c ~= 0] whileTrue:[        
     cn := s & c.
     s := s bitXor: c.
     c := cn<<1.
     c := c & 16rFFFFFFFF.
     s := s & 16rFFFFFFFF.
  ].
  s           

The loop is for carry propagation. The masks ensure that signed integers are handled (without them, only unsigned numbers are possibe). They also define the word length, the above being for 32bit operation. If you prefer 68bit addition, change to 16rFFFFFFFFFFFFFFFFF.

golf version (123 chars) (avoids the long mask by reusing in m):

[:a :b||s c n m|s:=a bitXor:b.c:=(a&b)<<1.[c~=0]whileTrue:[n:=s&c.s:=s bitXor:c.c:=n<<1.c:=c&m:=16rFFFFFFFF.s:=s&m].s]

(*) By using -1 instead of 16rFFFFFFFF, we can golf better, but the code no longer works for arbitrary precision numbers, only for machine-word sized smallIntegers (the representation for largeIntegers is not defined in the Ansi standard):

[:a :b||s c n|s:=a bitXor:b.c:=(a&b)<<1.[c~=0]whileTrue:[n:=s&c.s:=s bitXor:c.c:=n<<1.c:=c&-1.s:=s&-1].s]

this brings the code size down to 105 chars.

share|improve this answer
    
This is code-golf, so golf your answer. –  Victor Feb 16 at 9:55
1  
no chance to win, but I'll do it for you ;-) –  blabla999 Feb 16 at 15:09
    
Nice to see a Smalltalk answer! –  toothbrush Feb 16 at 18:25

Javascript (67)

There is probably much better

a=Array;p=Number;r=prompt;alert(a(p(r())).concat(a(p(r()))).length)
share|improve this answer
    
You shouldn't give a definitive answer without knowing if it needs floats or not. And it wont handle NaN's. But its quite a nice code! –  Ismael Miguel Feb 16 at 1:17
    
I think all the joins are unnecessary. The Array constructor makes an array of undefineds, which can be counted: a=Array;p=parseInt;r=prompt;alert(a(p(r())).concat(a(p(r()))).length) –  Ben Reich Feb 16 at 1:30
    
@BenReich, you're right, thanks –  Mig Feb 16 at 1:31
    
@Michael Also, the Number constructor saves 2 characters over parseInt –  Ben Reich Feb 16 at 1:35
    
@Michael Also, if you remove the alert, the output would still go to the console, but that makes the answer a little bit less fun. You could also reuse the prompt variable instead of alert, (the constructor alerts the argument with the prompt). Anyway, nice answer! –  Ben Reich Feb 16 at 1:39

Ruby, 18 chars

a.times{b=b.next}

And two more verbose variants, 29 chars

[*1..a].concat([*1..b]).size

Another version, 32 chars

(''.rjust(a)<<''.rjust(b)).size
share|improve this answer

APL, 8 and 12

Nothing new here, the array counting version:

{≢∊⍳¨⍺⍵}

and the log ○ log version:

{⍟⍟(**⍺)**⍵}

I just thought they looked cool in APL!

{≢     }       count
  ∊            all the elements in
   ⍳¨          the (two) sequences of naturals from 1 up to
     ⍺⍵        both arguments

 

{⍟⍟        }   the double logarithm of
   (**⍺)       the double exponential of ⍺
        *      raised to
         *⍵    the exponential of ⍵
share|improve this answer
2  
To be fair, everything looks cool in APL. –  Michael Stern Feb 19 at 21:09

dash (18)

time -f%e sleep $@

Requires GNU time 1.7 or higher.

Note that this will not work in b​ash, since its builtin time command differs from GNU time.

Usage

$ dash add.sh 42 58
100.00
share|improve this answer
    
what happens if one of the inputs is negative? –  Michael Stern Feb 16 at 3:46
2  
It fails. Just like all the other answers. –  Dennis Feb 16 at 3:47
3  
Drats! I hoped it gave the result before the question was asked. –  Tobia Feb 16 at 23:08
    
Yeah. I also was in high hopes that by inserting random sleep -3 I could speed up my programs. What a let-down. –  Alfe Feb 17 at 10:24

Postscript, 41

We define function with expression 41 bytes long as:

/a{0 moveto 0 rmoveto currentpoint pop}def

Then we call it e.g. as:

gs -q -dBATCH -c '/a{0 moveto 0 rmoveto currentpoint pop}def' -c '10 15 a ='

Which gives

25.0

It easily handles negatives and floats, unlike most competitors:-)

share|improve this answer

Ruby 39

f=->a,b{[*1..a].concat([*1..b]).length}
share|improve this answer

c

At least I've tried.

main(a,b){scanf("%d%d", &a,&b);
              switch(a){ 
                          case 1: 
                          switch(b)
                          {
                            case 1: return 2;
                            case 2: return 3;
                            case 3: return 4;
                            case 4: return 5;
                            //...
                           }
                          case 2:   
                            switch(b)
                          {
                            case 1: return 3;
                            case 2: return 4;
                            case 3: return 5;
                            case 4: return 6;
                            //...
                           }  
                         }                             

inspired by this answer

share|improve this answer

TI-BASIC, 19

Adds X and Y

log(log((e^e^X)^e^Y
share|improve this answer
1  
You sure know how to copy solutions: codegolf.stackexchange.com/a/21033/9498 –  Quincunx Feb 19 at 9:39

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.

share|improve this answer

Python 16 (Using Cheat)

print sum((a,b))

Python 36 (Using Tricks)

print len("%%0%dd%%0%dd"%(5,7)%(0,0))
share|improve this answer

Perl 28

print length('0'x$a.'0'x$b);
share|improve this answer
    
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 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
share|improve this answer
3  
you are using the - operator. –  Mhmd Feb 16 at 14:15

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)

share|improve this answer

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.

share|improve this answer
1  
Well, it looks like we had the same idea =) –  Matteo Italia Feb 17 at 8:36

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.

share|improve this answer

TI Basic 89 - 19 bytes

Run this in your TI-89 (Home screen or programming app):

ln(ln((e^e^x)^e^y))

This uses log rules to compute x+y, just like in this solution. As a bonus, it works for decimal and integer numbers. It works for all real numbers. If the logarithm rules are still valid with complex exponents, then this works for complex numbers too. However, my calculator spits out junk when I try to insert complex exponents.

share|improve this answer
    
Isn't ln 1 byte in TI Basic? Also, you can drop the closing parentheses, bringing this down to 15 bytes. –  ɐɔıʇǝɥʇuʎs May 6 at 9:22

Thanks to Michael Stern for teaching me Mathematica notation.

Mathematica - 21 20 bytes

Log@Log[(E^E^x)^E^y]

This uses the same approach as this solution, but it is in Mathematica to make it shorter. This works for negative and floating point numbers as well as integers in x and y.

Simplifying the expression using log rules yields x+y, but this is valid since it uses exponentiation, not one of the 4 basic operators.

share|improve this answer
    
Are you sure it works for complex numbers? –  Michael Stern Feb 20 at 2:42
    
@MichaelStern I'm 95% sure. –  Quincunx Feb 20 at 6:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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