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

40

7

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

TheDoctor

Posted 2014-02-16T00:37:14.160

Reputation: 7 793

Do Brainf**k's + and - count? – ASCIIThenANSI – 2015-05-19T14:09:21.500

2Define "number". Any integer? Non-negative integers? Do they have to be base-10? – SuperJedi224 – 2017-01-20T13:44:00.567

Will it have floats? – Ismael Miguel – 2014-02-16T01:06:19.980

@IsmaelMiguel - Nope. No floats. – TheDoctor – 2014-02-16T03:09:58.457

7Will it have negative numbers? (Currently, all the answers assume that the numbers will be positive, so you probably shouldn't change that) – Doorknob – 2014-02-16T03:48:21.190

@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 – 2014-02-16T03:55:36.380

I'd like to suggest that the title be changed to Add without addition, multiplication, subtraction, or division! or something similar (maybe Add without +*-/) to reflect that we cannot use those operators as well. – Justin – 2014-02-16T08:27:19.557

a=lambda x,y:'%s%s'%(x,y) – nyuszika7h – 2014-02-16T10:30:01.780

Related: Adding without using a + or - sign

– Ilmari Karonen – 2014-02-16T15:28:12.617

4

What about the mathematical solutions? You forgot to list those! This integrates, and this plays with logarithms

– Justin – 2014-02-17T00:54:41.053

3

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 [tag:code-golf], thus you are obliged to accept the shortest solution.

– Justin – 2014-02-20T21:01:55.193

I chose that solution because it dealt with negative numbers and it didn't use array concatenation, like the 4 char Golfscript – TheDoctor – 2014-02-20T21:26:08.223

Do FMAs count as replacements for + and *? – me' – 2019-09-20T11:23:21.423

Answers

2

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

blabla999

Posted 2014-02-16T00:37:14.160

Reputation: 1 869

45

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.

dave

Posted 2014-02-16T00:37:14.160

Reputation: 551

Good one, works in a whole bunch of other languages too. – trutheality – 2014-02-16T07:09:47.323

Wouldn't while(y){...} be shorter? – Niet the Dark Absol – 2014-02-16T14:37:08.537

You are correct, changed the do while to while – dave – 2014-02-16T16:04:12.890

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 – 2014-02-16T16:08:29.897

I was going to add the PHP version, but I just found out it's already been posted. +1 to you. The PHP version: while($y){$x^=$y;$y=($y&$x^$y)<<1;} - 36 – Amal Murali – 2014-02-16T16:42:26.683

1

More readable version of the code: Add two numbers without using arithmetic operators.

– Franck Dernoncourt – 2014-02-16T16:49:03.087

Slightly smaller: while(x^=y,y=(y&x^y)<<1)! – Toothbrush – 2014-02-16T22:54:56.160

@toothbrush in that case you need a ; at the end, otherwise the statement is not complete (OP's doesn't) – Tobia – 2014-02-16T23:38:58.650

@Tobia Not if it's the last statement! – Toothbrush – 2014-02-16T23:53:19.923

@toothbrush then why does it give a syntax error if I type it into Chrome's javascript console without the ;, but it works with the ;? – Tobia – 2014-02-17T00:00:55.220

@Tobia It doesn't give me a syntax error in Firefox's JavaScript console. I didn't try it in Google Chrome. – Toothbrush – 2014-02-17T00:03:08.400

1Or 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 – 2014-02-17T00:37:50.953

i almost want to downvote - this is a pretty explicit way of writing a + b = a + b (bit by bit) + the 1's to carry, shifted up - in other words it is literally how you do addition in primary school - the xor is doing (by definition) bitwise addition, which breaks the rules imho. On the other hand i just realised i can do addition by remembering only two numbers at a time. – user3125280 – 2014-02-17T11:03:49.480

3@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 – 2014-02-17T16:18:40.213

@BrianS obviously - and there's no need to be rude is there? - but think about it in base 10 for example. In 123 + 456, the x^=y is the same as x = (1+4 mod 10)(2+5 mod 10)(3+6 mod 10) = 579. It is just something to consider - xor is a basic math operation (addition), and it is called bitwise (meaning digitwise) because it operates, well, bitwise, rather than numberwise - not because it is something completely different to addition . – user3125280 – 2014-02-17T19:28:20.740

8@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 – 2014-02-17T19:33:41.840

@BrianS having reread the question, I do agree with you - but xor is and always was addition modulo 2 though not really 'basic arithmetic'. Many programmers see the bitwise operations as somewhat mystic, non arithmetic devices (hence the attention this answer has drawn) but I don't consider this the case. Obviously xor is certainly not what people call addition. Also + without + isn't completely nonsensical - if h f(g(a),g(b)) = h(g(a)) + h(g(b)), for example as in h = length, f = concat, g makes a list or h = log, f = log (E^x)^y, g=E^x, but that's not the point I was making. – user3125280 – 2014-02-18T10:23:13.997

@Exactly, he says which operators are permitted so any others, such as increment, decrement are also permitted. – QuentinUK – 2014-02-18T18:22:40.787

3for(;y;y=(y&x^y)<<1)x^=y is 1 byte shorter :) – William Barbosa – 2014-10-15T18:10:39.230

22

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.

syb0rg

Posted 2014-02-16T00:37:14.160

Reputation: 1 080

3You 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 – 2014-02-16T08:06:13.033

17

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.

Justin

Posted 2014-02-16T00:37:14.160

Reputation: 19 757

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 Stafusa – 2014-02-16T07:30:20.507

4@Victor I created the formula on my own. I remember math very clearly. – Justin – 2014-02-16T07:31:46.793

1Your 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 – 2014-02-16T12:23:23.917

"If I am allowed to assume input by placement in variables x and y.." I think you can - others do so as well. – blabla999 – 2014-02-16T17:38:41.163

@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 – 2014-02-16T17:54:29.410

@MichaelStern What is this @ notation? – Justin – 2014-02-19T09:34:28.463

@Quincunx @ is Mathematica shorthand for the Apply command. Thus you can multiply two numbers in 18 characters with Apply[Times, {2, 3}], or in 12 characters with Times[{2, 3}] or, using @ notation, in 11 characters with Times@{2, 3} (or of course, in this trivial example, in three characters with 2*3). – Michael Stern – 2014-02-19T17:56:04.713

@MichaelStern Does that mean that the Mathematica solution can become Log@Log[(E^E^x)^E^y]? – Justin – 2014-02-19T19:10:43.987

@Quincunx yes, Log@Log[(E^E^x)^E^y] for 20 characters. – Michael Stern – 2014-02-19T21:44:53.117

14

JavaScript [25 bytes]

~eval([1,~x,~y].join(''))

Andrew Templeton

Posted 2014-02-16T00:37:14.160

Reputation: 261

2Your 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 Stafusa – 2014-02-18T17:36:59.930

2Now it looks really good, I like it. Certainly is worth more upvotes. – VisioN – 2014-02-19T15:45:38.483

13

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.

Michael Stern

Posted 2014-02-16T00:37:14.160

Reputation: 3 029

2I love the integration! (although, strictly speaking this adds up something). +1 – blabla999 – 2014-02-16T03:54:25.533

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 – 2014-02-16T22:25:36.770

@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 – 2014-02-16T22:28:07.637

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 – 2014-02-16T22:37:22.653

3@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 – 2014-02-16T23:52:08.770

12

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.

Doorknob

Posted 2014-02-16T00:37:14.160

Reputation: 68 138

Does it work for negative numbers too? – Michael Stern – 2014-02-16T03:47:06.270

@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 – 2014-02-16T03:47:54.403

See my Mathematica solution. In the right language, solutions for negative numbers are possible. – Michael Stern – 2014-02-16T03:53:05.433

@MichaelStern LOL @ "right language" on this site of all places… – Tobia – 2014-02-16T23:05:28.287

10

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];}

ugoren

Posted 2014-02-16T00:37:14.160

Reputation: 16 527

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 – 2014-02-17T12:24:29.790

@hvd, Both work, at least on Linux 64bit. Integer parameters are extended to machine register size anyway. – ugoren – 2014-02-17T12:29:23.670

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 – 2014-02-17T12:32:48.030

8

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.

ASKASK

Posted 2014-02-16T00:37:14.160

Reputation: 291

-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. – Justin – 2014-02-16T05:15:09.280

@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 – 2014-02-16T05:42:17.697

3Reversed. Nice job. – Justin – 2014-02-16T05:43:49.253

6

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

James Wood

Posted 2014-02-16T00:37:14.160

Reputation: 406

5

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

user2846289

Posted 2014-02-16T00:37:14.160

Reputation: 1 541

4

Dash, 18 bytes

time -f%e sleep $@

Requires GNU time 1.7 or higher. Output is to STDERR.

Try it online!

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

At the cost of one additional byte, \time can be used instead of time to force Bash to use the external command.

Dennis

Posted 2014-02-16T00:37:14.160

Reputation: 196 637

What a pity! I had the same solution without knowing the question and thought, I could search for the fitting question. Partly this solution is wasted, because it allows even addition of floats in the shell - there it is a real handy replacement for the feature blown bc. Of course it works, just a bit longer, in bash with the full path (/usr/bin/time on my system.) – user unknown – 2018-03-25T01:32:32.693

1@userunknown \time should work as well in Bash. – Dennis – 2018-03-25T01:41:26.117

A great speedup :) (in typing). – user unknown – 2018-03-25T02:05:34.487

what happens if one of the inputs is negative? – Michael Stern – 2014-02-16T03:46:10.003

4It fails. Just like all the other answers. – Dennis – 2014-02-16T03:47:04.583

5Drats! I hoped it gave the result before the question was asked. – Tobia – 2014-02-16T23:08:46.657

3Yeah. I also was in high hopes that by inserting random sleep -3 I could speed up my programs. What a let-down. – Alfe – 2014-02-17T10:24:34.927

4

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.

blabla999

Posted 2014-02-16T00:37:14.160

Reputation: 1 869

This is code-golf, so golf your answer. – Victor Stafusa – 2014-02-16T09:55:43.350

1no chance to win, but I'll do it for you ;-) – blabla999 – 2014-02-16T15:09:35.553

Nice to see a Smalltalk answer! – Toothbrush – 2014-02-16T18:25:22.887

4

bash, 20 chars

(seq 10;seq 4)|wc -l

Nik O'Lai

Posted 2014-02-16T00:37:14.160

Reputation: 585

4

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 ⍵

Tobia

Posted 2014-02-16T00:37:14.160

Reputation: 5 455

2To be fair, everything looks cool in APL. – Michael Stern – 2014-02-19T21:09:56.857

You could make the first one a tacit prefix function for 5: ≢∘∊⍳¨ – Adám – 2019-07-25T10:38:13.673

@Adám Yes, but I don't like tacit functions and I find them difficult to read. – Tobia – 2019-07-27T10:35:19.130

@Tobia Maybe you don't like them because you find them difficult to read? I'm running a workshop on that… Have you seen my lesson on it?

– Adám – 2019-07-27T21:58:46.410

@Adám cool, thank you! Will check it out. – Tobia – 2019-08-08T16:29:25.203

@Adám Did check it out. My main gripe remains: trains are not legible. With traditional style, you can understand an expression incrementally as you read it, both left to right: ≢∊⍳... means "number of elements in the sequences..." and right to left: ...⍳¨⍺⍵ means "first generate sequences from ⎕IO to ⍺ and ⍵, then..." But with trains, you cannot begin to understand the expr until you have finished understanding every symbol in it and created the entire syntax tree in your mind, because a single mistake in the rightmost corner could (and does) shift the meaning for the entire train – Tobia – 2019-08-10T11:23:40.470

4

sed, 359 bytes (without the fancy formatting)

Sorry for the late answer, and probably the longest answer here by far. But I wanted to see if this is possible with sed:

                       s/([^ ]+) ([^ ]+)/\1:0::\2:/
                       :d /^([^:]+):\1::([^:]+):/tx
                       s/(:[^:]*)9([_:])/\1_\2/g;td
s/(:[^:]*)8(_*:)/\19\2/g;s/(:[^:]*)7(_*:)/\18\2/g;s/(:[^:]*)6(_*:)/\17\2/g
s/(:[^:]*)5(_*:)/\16\2/g;s/(:[^:]*)4(_*:)/\15\2/g;s/(:[^:]*)3(_*:)/\14\2/g
s/(:[^:]*)2(_*:)/\13\2/g;s/(:[^:]*)1(_*:)/\12\2/g;s/(:[^:]*)0(_*:)/\11\2/g
                       s/:(_+:)/:1\1/g; y/_/0/; # #
                       bd;  :x  s/.*::([^:]+):/\1/;
                       # # # # # # #  # # # # # # #

This is similar to https://codegolf.stackexchange.com/a/38087/11259, which simply increments numbers in a string. But instead it does the increment operations in a loop.

Input is taken from STDIN in the form "x y". That is first transformed to "x:0::y:". Then we increment all numbers that come after ":" characters, until we get "x:x::(x+y):". Then we finally return (x+y).

Output

$ printf "%s\n" "0 0" "0 1" "1 0" "9 999" "999 9" "12345 67890" "123 1000000000000000000000"  | sed -rf add.sed
0
1
1
1008
1008
80235
1000000000000000000123
$

Note that this only works for the natural numbers. However (in theory at least) it works for arbitrarily large integers. Because we are doing x increment operations on y, ordering can make a big difference to speed: x < y will be faster than x > y.

Digital Trauma

Posted 2014-02-16T00:37:14.160

Reputation: 64 644

3

Javascript (67)

There is probably much better

a=Array;p=Number;r=prompt;alert(a(p(r())).concat(a(p(r()))).length)

Michael M.

Posted 2014-02-16T00:37:14.160

Reputation: 12 173

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 – 2014-02-16T01:17:28.113

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 – 2014-02-16T01:30:18.437

@BenReich, you're right, thanks – Michael M. – 2014-02-16T01:31:37.760

@Michael Also, the Number constructor saves 2 characters over parseInt – Ben Reich – 2014-02-16T01:35:24.070

@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 – 2014-02-16T01:39:55.247

@Michael, Agree with the others, nice approach! One note, you can use |0 instead of using the Number constructor to save a few bytes: r=prompt;alert(Array(r()|0).concat(Array(r()|0)).length) – Dom Hastings – 2014-02-16T09:51:40.220

3

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

Nik O'Lai

Posted 2014-02-16T00:37:14.160

Reputation: 585

3

C# - on the fly code generation

Yeah, there is actually an addition in there, but not the + operator and not even a framework function which does adding, instead we generate a method on the fly that does the adding.

public static int Add(int i1, int i2)
{
    var dm = new DynamicMethod("add", typeof(int), new[] { typeof(int), typeof(int) });
    var ilg = dm.GetILGenerator();
    ilg.Emit(OpCodes.Ldarg_0);
    ilg.Emit(OpCodes.Ldarg_1);
    ilg.Emit(OpCodes.Add);
    ilg.Emit(OpCodes.Ret);
    var del = (Func<int, int, int>)dm.CreateDelegate(typeof(Func<int, int, int>));
    return del(i1, i2);
}

fejesjoco

Posted 2014-02-16T00:37:14.160

Reputation: 5 174

2

Pyth, 29 bytes

AQW!qG0=k.&GH=HxGH=k.<k1=Gk)H

Try it online!

My first submission here!

This compiles to:

assign('Q',eval_input())     # Q
assign('[G,H]',Q)            #A
while Pnot(equal(G,0)):      #  W!qG0
  assign('k',bitand(G,H))    #       =k.&GH
  assign('H',index(G,H))     #             =HxGH  (index in this case is XOR)
  assign('k',leftshift(k,1)) #                  =k.<k1
  assign('G',k)              #                        =Gk)
imp_print(H)                 #                            H

bengdahl

Posted 2014-02-16T00:37:14.160

Reputation: 21

1Welcome to the site! – Post Rock Garf Hunter – 2018-02-07T15:14:57.340

2

PowerShell, 22 bytes

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

Try it online!

Where * is an repeat element operator.

mazzy

Posted 2014-02-16T00:37:14.160

Reputation: 4 832

2

Ruby 39

f=->a,b{[*1..a].concat([*1..b]).length}

Hauleth

Posted 2014-02-16T00:37:14.160

Reputation: 1 472

2

Python -- 22 characters

len(range(x)+range(y))

pydud

Posted 2014-02-16T00:37:14.160

Reputation: 21

1I think that counts as addition? – TheDoctor – 2014-02-17T02:32:32.370

1it's concatenation – pydud – 2014-02-17T02:32:49.347

2

TI-BASIC, 10

Adds X and Y

ln(ln(e^(e^(X))^e^(Y

Timtech

Posted 2014-02-16T00:37:14.160

Reputation: 12 038

First, this doesn't work because it uses log( instead of ln(. Second, it is actually ten bytes if written in the form ln(ln(e^(e^(X))^e^(Y. – lirtosiast – 2015-05-16T19:40:05.553

1

You sure know how to copy solutions: http://codegolf.stackexchange.com/a/21033/9498

– Justin – 2014-02-19T09:39:34.740

2

R 36

function(x,y)length(rep(1:2,c(x,y)))

where rep builds a vector of x ones followed by y twos.

flodel

Posted 2014-02-16T00:37:14.160

Reputation: 2 345

2You can make a program that does the same a bit shorter: length(rep(1:2,scan())) – Masclins – 2016-05-06T09:59:08.747

2

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.

Justin

Posted 2014-02-16T00:37:14.160

Reputation: 19 757

Are you sure it works for complex numbers? – Michael Stern – 2014-02-20T02:42:55.183

2

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.

Justin

Posted 2014-02-16T00:37:14.160

Reputation: 19 757

3Isn't ln 1 byte in TI Basic? Also, you can drop the closing parentheses, bringing this down to 15 bytes. – ɐɔıʇǝɥʇuʎs – 2014-05-06T09:22:02.723

2

C# - string arithmetics

We convert both numbers to strings, do the addition with string cutting (with carry and everything, you know), then parse back to integer. Tested with i1, i2 in 0..200, works like a charm. Find an addition in this one!

public static int Add(int i1, int i2)
{
    var s1 = new string(i1.ToString().Reverse().ToArray());
    var s2 = new string(i2.ToString().Reverse().ToArray());
    var nums = "01234567890123456789";
    var c = '0';
    var ret = new StringBuilder();
    while (s1.Length > 0 || s2.Length > 0 || c != '0')
    {
        var c1 = s1.Length > 0 ? s1[0] : '0';
        var c2 = s2.Length > 0 ? s2[0] : '0';
        var s = nums;
        s = s.Substring(int.Parse(c1.ToString()));
        s = s.Substring(int.Parse(c2.ToString()));
        s = s.Substring(int.Parse(c.ToString()));
        ret.Append(s[0]);
        if (s1.Length > 0)
            s1 = s1.Substring(1);
        if (s2.Length > 0)
            s2 = s2.Substring(1);
        c = s.Length <= 10 ? '1' : '0';
    }
    return int.Parse(new string(ret.ToString().ToCharArray().Reverse().ToArray()));
}

fejesjoco

Posted 2014-02-16T00:37:14.160

Reputation: 5 174

2

C (79)

void main(){int a,b;scanf("%d%d",&a,&b);printf("%d",printf("%*c%*c",a,0,b,0));}

Pruthvi Raj

Posted 2014-02-16T00:37:14.160

Reputation: 141

2

APL: 2

1⊥

This converts the numbers from base 1, so (n*1^1)+(m*1^2) which is exactly n+m.

Can be tried on TryApl.org

Moris Zucca

Posted 2014-02-16T00:37:14.160

Reputation: 1 519

2

K, 2 bytes

#&

Usage example:

  #&7 212
219

Apply the "where" operator (monadic &) to the numbers in an input list (possibly taking liberty with the input format). This will produce a list containing the first number of zeroes followed by the second number of ones:

  &3 2
0 0 0 1 1

Normally this operator is used as a "gather" to produce a list of the indices of the nonzero elements of a boolean list, but the generalized form comes in handy occasionally.

Then simply take the count of that list (monadic #).

If my interpretation of the input requirements is unacceptable, the following slightly longer solution does the same trick:

{#&x,y}

JohnE

Posted 2014-02-16T00:37:14.160

Reputation: 4 632

1

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

12Me21

Posted 2014-02-16T00:37:14.160

Reputation: 6 110

1

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.

sprra

Posted 2014-02-16T00:37:14.160

Reputation: 11

1

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.

Gabriel Mills

Posted 2014-02-16T00:37:14.160

Reputation: 778

1

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

Matthew Jensen

Posted 2014-02-16T00:37:14.160

Reputation: 713

1

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.

Lyxal

Posted 2014-02-16T00:37:14.160

Reputation: 5 253

1

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.

user12205

Posted 2014-02-16T00:37:14.160

Reputation: 8 752

1

Python 16 (Using Cheat)

print sum((a,b))

Python 36 (Using Tricks)

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

Abhijit

Posted 2014-02-16T00:37:14.160

Reputation: 2 841

1

Perl 28

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

Abhijit

Posted 2014-02-16T00:37:14.160

Reputation: 2 841

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 – 2014-02-16T09:55:24.627

1

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

WeSee

Posted 2014-02-16T00:37:14.160

Reputation: 111

4you are using the - operator. – Mhmd – 2014-02-16T14:15:33.583

1

JavaScript [32 bytes]

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

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

VisioN

Posted 2014-02-16T00:37:14.160

Reputation: 4 490

Or more interactive in 54 bytes: p=prompt,alert(Array(+p()).concat(Array(+p())).length). – VisioN – 2014-02-16T17:58:32.650

1

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.

tmartin

Posted 2014-02-16T00:37:14.160

Reputation: 3 917

You can avoid the need to raze if you use "where"- check out my K solution! – JohnE – 2015-05-31T02:24:49.050

1

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)

Matteo Italia

Posted 2014-02-16T00:37:14.160

Reputation: 3 669

1

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.

Erikster

Posted 2014-02-16T00:37:14.160

Reputation: 41

1

Well, it looks like we had the same idea =)

– Matteo Italia – 2014-02-17T08:36:22.903

1@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 – 2019-12-11T19:12:15.407

1

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.

A. Bellmunt

Posted 2014-02-16T00:37:14.160

Reputation: 111

1

Excel - 31

(presuming numbers in cells A1 and A2)

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

The digital equivalent of counting on fingers. :)

Allen Gould

Posted 2014-02-16T00:37:14.160

Reputation: 131

1

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.

DLosc

Posted 2014-02-16T00:37:14.160

Reputation: 21 213

1

Python 3, 46 Bytes

def s(a,b):
 for i in range(b):a=-~a
 return a

Mega Man

Posted 2014-02-16T00:37:14.160

Reputation: 1 379

0

Turing Machine Code, 1184 bytes

A golfed version of a machine I posted to my googology wiki user blog a while ago. Supports signed ints. Try it online!

0 _ * l B
0 - * r AAA
0 * * r *
B 0 9 l *
B 9 8 r C
B 8 7 r C
B 7 6 r C
B 6 5 r C
B 5 4 r C
B 4 3 r C
B 3 2 r C
B 2 1 r C
B 1 0 r C
B _ * r AA
B * * * AA
C _ * r D
C * * r *
D _ * l E
D - * r 8
D * * r *
E 0 1 l F
E 1 2 l F
E 2 3 l F
E 3 4 l F
E 4 5 l F
E 5 6 l F
E 6 7 l F
E 7 8 l F
E 8 9 l F
E 9 0 l *
E _ * r S1
E M * r S1
F _ * l B
F * * l *
AA _ * r BB
AA * _ r *
BB M - * halt
BB * * * halt
S1 0 1 r S0
S0 0 0 r S0
S0 _ 0 * F 
AAA 0 9 l *
AAA 9 8 r BBB
AAA 8 7 r BBB
AAA 7 6 r BBB
AAA 6 5 r BBB
AAA 5 4 r BBB
AAA 4 3 r BBB
AAA 3 2 r BBB
AAA 2 1 r BBB
AAA 1 0 r BBB
AAA _ * r BB
AAA * * * BB
BBB _ * r CCC
BBB * * r *
CCC _ * l DDD
CCC - * * ZZZ
CCC * * r *
DDD 9 8 l EEE
DDD 8 7 l EEE
DDD 7 6 l EEE
DDD 6 5 l EEE
DDD 5 4 l EEE
DDD 4 3 l EEE
DDD 3 2 l EEE
DDD 2 1 l EEE
DDD 1 0 l EEE
DDD 0 9 l *
DDD _ * r FFF
EEE _ * l *
EEE * * * AAA
FFF _ * * GGG
FFF * _ r *
GGG _ * l *
GGG * * * HHH
HHH 0 1 * halt
HHH 1 2 * halt
HHH 2 3 * halt
HHH 3 4 * halt
HHH 4 5 * halt
HHH 5 6 * halt
HHH 6 7 * halt
HHH 7 8 * halt
HHH 8 9 * halt
HHH 9 0 l *
8 _ * l 9
8 * * r * 
9 9 8 l F
9 8 7 l F
9 7 6 l F
9 6 5 l F
9 5 4 l F
9 4 3 l F
9 3 2 l F
9 2 1 l F
9 1 0 l F
9 0 9 l *
9 * * * FFF
ZZZ * M r E

SuperJedi224

Posted 2014-02-16T00:37:14.160

Reputation: 11 342

can't you use shorter state names :| – ASCII-only – 2019-04-12T07:18:23.537

0

Ruby, 41 20 bytes

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

Try it online!

G B

Posted 2014-02-16T00:37:14.160

Reputation: 11 099

0

Julia, 29 bytes

a$b=next(countfrom(a,b),a)[2]

Julia has iterators that can count up by an arbitrary amount at a time. It's usually used to create arithmetic sequences, but it can be definitely pressed into service as a ersatz adder.

eaglgenes101

Posted 2014-02-16T00:37:14.160

Reputation: 577

0

Octave, 62 39 bytes

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

Unsigned integers only. Try it online!

ceilingcat

Posted 2014-02-16T00:37:14.160

Reputation: 5 503

0

Java 8, 42 bytes

(x,y)->{for(int c;y!=0;c=x&y,x^=y,y=c<<1);return x;};

Try it online!
Based on https://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/

Benjamin Urquhart

Posted 2014-02-16T00:37:14.160

Reputation: 1 262

0

Python 2 & 3, 39 30 bytes (function)

lambda x,y:eval("-~"*x+str(y))

Try it online!

The -, * and + are negation, string repetition and string concatenation respectively, not mathematical operators.

Explanation

-~y effectively increments y, so doing -~-~...-~-~y x times increments y x times.


These two are just for fun c:

Python 2, 54  45 bytes (program)

x,y=input(),str(input());print eval("-~"*x+y)

Python 3, 55 46 bytes (program)

x,y=int(input()),input();print(eval("-~"*x+y))

Sagittarius

Posted 2014-02-16T00:37:14.160

Reputation: 169

while i was writing that i realized it doesn't work for negative numbers, is that a problem? – Sagittarius – 2019-08-31T13:16:39.393

@A_ oh i was thinking about doing that but i ruled it out pretty quickly because i thought the - counted as a mathematical operator; ill edit it – Sagittarius – 2019-08-31T22:49:17.247

The unary - is a negation operator, and I don't think that counts as a math operator. – None – 2019-08-31T23:40:35.610

0

W, 6 5 bytes

1.MJk

Explanation

  M   % Map the (implicit) input with ...
1.    % generate a list with this length
   J  % Join the array (NOT using the error-proof apply addition.)
    k % Find the length of the array

user85052

Posted 2014-02-16T00:37:14.160

Reputation:

0

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

Victor Stafusa

Posted 2014-02-16T00:37:14.160

Reputation: 8 612

2Those use the + and - operators. y-- is the same as y=y-1 and x++ is the same as x=x+1. – Ismael Miguel – 2014-02-16T07:15:38.243

@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 – 2014-02-16T07:24:35.640

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 – 2014-02-16T07:34:15.700

@IsmaelMiguel See this: http://www.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 – 2014-02-16T07:43:40.027

And by the way, in mathematics addition is normally defined in terms of the successor function/operation, and not the other way around. – Victor Stafusa – 2014-02-16T07:46:47.790

I also think, this is slightly unfair, and I would see += as "syntactic sugar" for the + function. Also, when arguing with succ/pred, then I'd go for peano numbers. – blabla999 – 2014-02-16T17:36:06.280

2I 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 – 2014-02-17T12:16:41.700

0

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.

Ismael Miguel

Posted 2014-02-16T00:37:14.160

Reputation: 6 797

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 – 2014-02-16T08:46:30.600

Save 6 chars: Instead of _(a,b,c,d,l), use just _(a,b). – Victor Stafusa – 2014-02-16T08:48:44.827

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 – 2014-02-16T22:13:58.743

“Basically, it isn't an arithmetic operator anymore!” Yeah, it is. Almost unarguably. – Ry- – 2014-02-20T01:13:15.240

Not really. It's Number+Boolean. Try writing this in a math test: '0=a*False'. – Ismael Miguel – 2014-02-20T01:15:07.833

0

int Ad(int a,int b){while(b){int c=a & b;a=a ^ b;b=c<<1;}return a;}

Aatish Sai

Posted 2014-02-16T00:37:14.160

Reputation: 101

1This is [tag:code-golf], you are supposed to make the code as short as possible, try removing the whitespace, for instance. – mniip – 2014-02-16T15:29:57.893

0

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);
    }
}

Albert Renshaw

Posted 2014-02-16T00:37:14.160

Reputation: 2 955

1I 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 – 2014-02-17T23:14:22.923

0

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)

Person93

Posted 2014-02-16T00:37:14.160

Reputation: 171

0

F# - 36

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

The + here is not addition, but string concatenation.

p.s.w.g

Posted 2014-02-16T00:37:14.160

Reputation: 573

0

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

unclemeat

Posted 2014-02-16T00:37:14.160

Reputation: 2 302

0

Go [43 bytes]

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

Kristoffer Sall-Storgaard

Posted 2014-02-16T00:37:14.160

Reputation: 489

0

Perl, 38 chars

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

Leo Pflug

Posted 2014-02-16T00:37:14.160

Reputation: 185

0

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)

epson121

Posted 2014-02-16T00:37:14.160

Reputation: 171

0

C, 14 bytes

while(x--)y++;

Avoids +, -, * and /.

Note that ++ and -- compile to machine code for INCR and DECR, so there is no addition or subtraction.

QuentinUK

Posted 2014-02-16T00:37:14.160

Reputation: 109

2

Not novel: http://codegolf.stackexchange.com/a/21029/3755

– Victor Stafusa – 2014-02-18T17:30:52.703

@victor I did not copy your answer. Actually my answer is in C. It is 1 byte longer than yours. – QuentinUK – 2014-02-18T18:45:06.477

0

JAVA, 79 bytes

int Add(int x, int y){while (y != 0){int carry=x&y;x=x^y;y=carry<<1;}return x;}

Viswanath Lekshmanan

Posted 2014-02-16T00:37:14.160

Reputation: 157

0

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)

ɐɔıʇǝɥʇuʎs

Posted 2014-02-16T00:37:14.160

Reputation: 4 449

0

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

cjfaure

Posted 2014-02-16T00:37:14.160

Reputation: 4 213

0

Python 3, 27 bytes

len("".join(["."*x,"."*y]))

where x is input 1 and y is input 2

(Okay, okay fine it's really 49 bytes including "true code":

len("".join(["."*int(input()),"."*int(input())]))

Note that * is for string duplication, although that might be a "standard operator"

parzivail

Posted 2014-02-16T00:37:14.160

Reputation: 71

0

Dart - 30

s(a,b)=>a>0?s((a&b)<<1,a^b):b;

After writing this, I realized it was equivalent to the JavaScript solution already posted above - and because Dart has bignums, not just int32, it doesn't work for negative numbers. So, not a big win :(

Termination can be proven by seeing that the number of bits in a and b together reduces for each iteration until a becomes zero.

lrn

Posted 2014-02-16T00:37:14.160

Reputation: 521

0

Microscript, 9 bytes

A variant of the array concatenation solution (although this one uses a stack.)

ics]ics]#

Technically not a valid competing entry, however; as the language is too new.

Requires that both inputs be nonnegative.


A seven-byte version using a new command added shortly after I originally posted this:

i$si$s#

SuperJedi224

Posted 2014-02-16T00:37:14.160

Reputation: 11 342

0

X86 (2)

rep movb two bytes f3 A4,

adds ecx to esi (and to edi) result in esi but has side-effects if ds:esi != es:edi

Jasen

Posted 2014-02-16T00:37:14.160

Reputation: 413

0

Python 2, Python 3, 41 bytes

i,j=input(),input()
while j>0:i=-~i;j=~-j

If using the - number operator is allowed.


Python 2, Python 3, 40 bytes

i,j=input(),input()
while j>0:i=-~i;j-=1

If using the - number and literal -= number operators is allowed.


Works on positive integers. Takes a and b and prints a+b.

Erik the Outgolfer

Posted 2014-02-16T00:37:14.160

Reputation: 38 134

0

PHP, 91 78 51 bytes

bit logic and shifting ... what else?

function p($x,$y){return$y?p($x^$y,($x&$y)<<1):$x;}

also works for negative integers

Titus

Posted 2014-02-16T00:37:14.160

Reputation: 13 814

0

Haskell, 25 bytes

n+m=length$[1..m]++[1..n]

We can no longer use the old +? No problem, we can just define a new one. This approach doesn't work with negative numbers, I have yet to figure out something else for them.

Laikoni

Posted 2014-02-16T00:37:14.160

Reputation: 23 676

0

R, 80 bytes

Went for a recursive function doing bit operations.

f=function(a,b){d=bitwXor(a,b);e=bitwShiftL(bitwAnd(a,b),1);ifelse(!e,d,f(d,e))}

Ungolfed:

f=function(a,b){
    d=bitwXor(a,b)            # xors a and b.(tells us bits that are 1 in end)
    f=bitwAnd(a,b)            # tells us which bits need to carry over 1
    e=bitwShiftL(e,1)         # carries those bits over
    if (e==0) d else f(d,e)   # if carried nothing, return xored bits. 
}                             # otherwise, recursively call fn on xored and
                              # carried bits.

It would have been shorter -- but R really does not intend for bit operations.

user5957401

Posted 2014-02-16T00:37:14.160

Reputation: 699

-1

Java, 85 bytes

import java.math.*;class a{BigInteger A(BigInteger b,BigInteger B){return b.add(B);}}

BigInteger isn't located in java.lang, java.util, java.io (is it even possible for a numeric type to be related to I/O?) or their subpackages, so its add method doesn't count as a language feature. Problem?

user8397947

Posted 2014-02-16T00:37:14.160

Reputation: 1 242