Adding without using a + or - sign

24

7

There have been many "Do __ without __" challenges before, but I hope that this is one of the most challenging.

The Challenge

You are to write a program that takes two natural numbers (whole numbers > 0) from STDIN, and prints the sum of the two numbers to STDOUT. The challenge is that you must use as few + and - signs as possible. You are not allowed to use any sum-like or negation functions.

Examples

input

123
468

output

591

input

702
720

output

1422

Tie Breaker: If two programs have the same number of + and - characters, the winner is the person with fewer / * ( ) = . , and 0-9 characters.

Not Allowed: Languages in which the standard addition/subtraction and increment/decrement operators are symbols other than + or - are not allowed. This means that Whitespace the language is not allowed.

PhiNotPi

Posted 2011-11-30T23:09:47.133

Reputation: 26 739

Concatenating strings works? – user75200 – 2018-01-06T20:06:29.130

Are languages allowed that don't have arithmetic operators at all? I think that last sentence permits them, but it's not completely clear. – Toby Speight – 2018-08-01T15:39:43.603

Fewer ( and ) puts Lisps at a disadvantage. :( – Joshua Taylor – 2014-02-20T21:05:34.683

Next challenge would be "Comparing two numbers without any of ><+-*/%&|" – Naruyoko – 2019-09-19T23:41:33.640

1Perhaps this challenge was a lot easier than I thought it would be, especially in other languages, where there are sum() functions. I have to fix this. – PhiNotPi – 2011-12-01T00:45:46.310

50100 rep bounty for anybody who can do this in Brainfuck. – Peter Olson – 2011-12-01T05:57:36.263

3@Peter Olson Well, I guess BF is not turing complete without either + or -... – FUZxxl – 2011-12-01T10:21:55.763

3Just to clarify, this challenge does not care about code length right? Only the number of +,- and tie breaker characters? ...or do you need to change the rules again :-) – Tommy – 2011-12-01T19:39:51.977

@Tommy No, it does not. – PhiNotPi – 2011-12-01T21:58:45.160

@PeterOlson: I'd be even more impressed if someone can do it in Malbolge

– Kris – 2011-12-07T21:13:48.763

Answers

29

Perl (no +/-, no tie-breakers, 29 chars)

s!!xx!;s!x!$"x<>!eg;say y!!!c

As a bonus, you can make the code sum more than two numbers by adding more xs to the s!!xx!.

Alternatively, here are two 21-char solutions with 1 and 3 tie-breakers respectively

say length$"x<>.$"x<>

say log exp(<>)*exp<>

Note: These solutions use the say function, available since Perl 5.10.0 with the -E command line switch or with use 5.010. See the edit history of this answer for versions that work on older perls.


How does the solution with no tie-breakers work?

  • s!!xx! is a regexp replacement operator, operating by default on the $_ variable, which replaces the empty string with the string xx. (Usually / is used as the regexp delimiter in Perl, but really almost any character can be used. I chose ! since it's not a tie-breaker.) This is just a fancy way of prepending "xx" to $_ — or, since $_ starts out empty (undefined, actually), it's really a way to write $_ = "xx" without using the equals sign (and with one character less, too).

  • s!x!$"x<>!eg is another regexp replacement, this time replacing each x in $_ with the value of the expression $" x <>. (The g switch specifies global replacement, e specifies that the replacement is to be evaluated as Perl code instead of being used as a literal string.) $" is a special variable whose default value happens to be a single space; using it instead of " " saves one char. (Any other variable known to have a one-character value, such as $& or $/, would work equally well here, except that using $/ would cost me a tie-breaker.)

    The <> line input operator, in scalar context, reads one line from standard input and returns it. The x before it is the Perl string repetition operator, and is really the core of this solution: it returns its left operand (a single space character) repeated the number of times given by its right operand (the line we just read as input).

  • y!!!c is just an obscure way to (ab)use the transliteration operator to count the characters in a string ($_ by default, again). I could've just written say length, but the obfuscated version is one character shorter. :)

Ilmari Karonen

Posted 2011-11-30T23:09:47.133

Reputation: 19 513

1if character count is the final tie breaker, and many entries exist tied for zero in the other categories, doesn't this just become code-golf with some source restrictions? – Sparr – 2019-09-19T23:26:25.427

3+1 - awsome and totally unreadable ;-) This seems to be the perfect answer since the character count doesn't matter in this challenge. – Tommy – 2011-12-01T22:14:36.287

@Tommy, there are other perfect answers too. Maybe we should push for character count to be the final tie-breaker. – Peter Taylor – 2011-12-02T17:04:48.037

@Peter: I sort of assumed it already was, by default. – Ilmari Karonen – 2011-12-02T17:19:02.973

47

R (24 characters)

length(sequence(scan()))

What this does:

  • scan reads input from STDIN (or a file)
  • sequence generates integer sequences starting from 1 and concatenates the sequences. For example, sequence(c(2, 3)) results in the vector 1 2 1 2 3
  • length calculates the number of elements in the concatenated vector

Example 1:

> length(sequence(scan()))
1: 123
2: 468
3:
Read 2 items
[1] 591

Example 2:

> length(sequence(scan()))
1: 702
2: 720
3:
Read 2 items
[1] 1422

Andrie

Posted 2011-11-30T23:09:47.133

Reputation: 687

+/- and above mentioned tie-breakers are interesting, not characters. – user unknown – 2012-05-30T03:36:21.593

How does it calculate length? without using any addition? If so, I'd be surprised. – Tem Pora – 2013-09-28T10:12:01.387

2@TemPora The question only restricts the code in the answer, not the operations done behind the scenes. We're not going to restrict the question so the underlying computer architecture cannot increment a register. – mbomb007 – 2018-07-31T14:57:16.920

1Very clever, good job. – Matthew Read – 2011-12-01T21:34:26.397

This blows my mind – smci – 2012-01-21T09:25:27.880

15

D

main(){
    int a,b;
    readf("%d %d",&a,&b);
    while(b){a^=b;b=((a^b)&b)<<1;}
    write(a);
}

bit twiddling for the win

as a bonus the compiled code doesn't contain a add operation (can't speak for the readf call though)

ratchet freak

Posted 2011-11-30T23:09:47.133

Reputation: 1 334

12

Python 2, 43 bytes

print len('%s%s'%(input()*'?',input()*'!'))

Omar

Posted 2011-11-30T23:09:47.133

Reputation: 1 154

3Very inventive, but you might want to change the character used in the string to something other than a tie-breaker such as "~" – 3Doubloons – 2011-12-01T05:36:49.850

Thanks for the advice Alex, I had already forgotten about the tie-breaker rule. – Omar – 2011-12-02T17:38:48.967

print sum(input(),input()) – razpeitia – 2011-12-03T02:52:37.300

9razpeitia: I think sum is a "sum-like" function and thus not allowed. – Omar – 2011-12-03T12:38:40.280

6

GolfScript

No +/- or tie-breakers:

# Twiddle some bits to get a few small integers
[]!~abs:two~abs:three!:zero~:minusone;

~[two base minusone%\two base minusone%]zip
zero:c;
{
    # Stack holds [x y] or [x] with implicit y is zero
    # Half adder using x y c: want to end up with sum on stack and carry back in c
    [~c zero]three<zero$
    ~^^\
    $~;:c;;
}%
[~c]minusone%two base

Much simpler version with two tie-breaker characters, using the same list-concatenation trick that other people are using:

~[\]{,~}%,

I'm assuming that GolfScript isn't disqualified for having ) as an increment operator, as I'm not actually using it.

Peter Taylor

Posted 2011-11-30T23:09:47.133

Reputation: 41 901

6

C (32bit only)

int main(int ac, char *av) {
    scanf("%d\n%d", &ac, &av);
    return printf("%d\n", &av[ac]);
}

Pointer arithmetic is just as good.
How does it match the requirements?
* No + or -
* No /, =, ., 0-9
* Only 3 pairs of parenthesis, which seems to me minimal (you need main, scanf, printf).
* One * (the pointer approach requires it).
* Four , (could save one by defining normal variables, not ac,av)

Uri Goren

Posted 2011-11-30T23:09:47.133

Reputation: 61

6

C++ 0 +/-, 3 tie-breakers

#include <vector>
#include <iostream>

#define WAX (
#define WANE )
#define SPOT .

int main WAX WANE {
    unsigned x;
    unsigned y;
    std::cin >> x >> y;
    std::vector<int> v WAX x WANE;
    std::vector<int> u WAX y WANE;
    for WAX auto n : u WANE {
        v SPOT push_back WAX n WANE;
    }
    std::cout << v SPOT size WAX WANE;
}

R. Martinho Fernandes

Posted 2011-11-30T23:09:47.133

Reputation: 2 135

5

Haskell, 0+2

import Monad
main = join $ fmap print $ fmap length $ fmap f $ fmap lines getContents
f x = join $ flip replicate [] `fmap` fmap read x

This uses no + or - characters, and only two = from the set of tie breaker characters, one of which is mandatory for binding main. The sum is done by concatenating lists of the appropriate lengths.

hammar

Posted 2011-11-30T23:09:47.133

Reputation: 4 011

4

EDIT This was posted BEFORE the rules changed to disallow sum...

The R language: No calls to + or -... And 9 tie-breaker characters!

sum(as.numeric(readLines(n=2)))

Example:

> sum(as.numeric(readLines(n=2)))
123
456
[1] 579

The [1] 579 is the answer 579 (the [1] is to keep track of where in the result vector your are since in R all values are vectors - in this case of length 1)

Note that R has + operators just like most languages - it just so happens that it has sum too that sums up a bunch of vectors.

In this case, readLines returns a string vector of length 2. I then coerce it to numeric (doubles) and sum it up...

Just to show some other features of R:

> 11:20 # Generate a sequence
 [1] 11 12 13 14 15 16 17 18 19 20

> sum(1:10, 101:110, pi)
[1] 1113.142

Tommy

Posted 2011-11-30T23:09:47.133

Reputation: 821

1+1 For making me have to change the rules to outlaw the sum() function. – PhiNotPi – 2011-12-01T00:48:37.257

@PhiNotPi - Changing the rules?! That's cheating! :-) ...But you should probably say "sum-like functions" or I'll just use colSums instead... Maybe also outlaw "negation-like functions" while your at it... – Tommy – 2011-12-01T00:53:35.103

2I'm going to take your advice. From what I can tell, everyone (including me) on this site loves to point out loopholes in the rules. – PhiNotPi – 2011-12-01T00:59:27.017

4

The R language

New rules, new answer, same language. No calls to + or -

UPDATE Using scan, it drops to 11 tie-breaker characters (and 27 characters in all).

as.numeric(scan())%*%c(1,1)

Original: 13 tie-breaker characters!

as.numeric(readLines(n=2)) %*% c(1,1)

Example:

> as.numeric(readLines(n=2)) %*% c(1,1)
123
456
     [,1]
[1,]  579

This time the result is achieved by matrix multiplication. The answer is displayed as a 1x1 matrix.

Tommy

Posted 2011-11-30T23:09:47.133

Reputation: 821

There's nothing that I can do to outlaw this. Perhaps R is just good at this challenge, since it is mostly mathematics-based. Or maybe this challenge is just easy. – PhiNotPi – 2011-12-01T01:14:08.047

+1 Nice. You can make this even shorter with scan() instead of readlines(n=2) – Andrie – 2011-12-01T21:53:30.137

@Andrie - yes, but then you rely on the user entering exactly two numbers... Which is OK for this challenge I guess... – Tommy – 2011-12-01T22:07:42.080

4

Haskell, 0 +/-, 6 2 tie-breakers (=)

(does not use the string/list concatenation trick)

main = interact f
f x = show $ log $ product $ map exp $ map read $ lines x

J B

Posted 2011-11-30T23:09:47.133

Reputation: 9 638

You can eliminate all the dots at the expense of an extra = by replacing the composition: instead of "f.g.h" write "a where a x = f$g$h x" – Omar – 2011-12-07T00:06:46.850

3

Seed, 3904 3846 11 bytes, 0 +/-, 10 tie breakers

4 141745954

Krzysztof Szewczyk

Posted 2011-11-30T23:09:47.133

Reputation: 3 819

3

Javascript, 56

p=prompt;alert(Array(~~p()).concat(Array(~~p())).length)

Thanks to @JiminP on the ~~ tip! I'm going for least bytes, so the 1 byte saving on the p=prompt; is still worth it. I understand your argument about tie-breaker chars, but to be honest wouldn't you rather the least bytes :-p

Version, 69

i=parseInt;p=prompt;alert(Array(i(p())).concat(Array(i(p()))).length)

Thanks to some feedback from @Ilmari and @JiminP, I've shaved 13 bytes off my original solution.

Originally, 82

i=parseInt;p=prompt;a=Array(i(p()));a.push.apply(a, Array(i(p())));alert(a.length)

stephencarmody

Posted 2011-11-30T23:09:47.133

Reputation: 41

That space after the comma is completely unnecessary; removing it gets you down to 81. – Ilmari Karonen – 2011-12-02T23:53:38.123

Using concat and put calculations in alert is shorter. i=parseInt;p=prompt;alert(Array(i(p())).concat(Array(i(p()))).length) BTW, I didn't know that Array(n) returns an array with length n. The Google Chrome console gave me [] and I thought there was nothing... – JiminP – 2011-12-03T00:29:55.990

1Oh, since the important thing is tie-breaker characters, p=prompt is not good. And, parseInt(x) is almost equivalent to ~~x. alert(Array(~~prompt())['concat'](Array(~~prompt()))['length']) (12 tie-breaker chars) PS. I could use this as my entry, but that just gives me feeling of stealing. – JiminP – 2011-12-04T14:14:23.710

3

C

b[500];i;j;main(){scanf("%d%d",&i,&j);printf("%d\n",sprintf(b,"%*s%*s",i,"",j,""));

Patrick

Posted 2011-11-30T23:09:47.133

Reputation: 221

3

APL (no +/-, no tie breakers, 8 or 10 characters)

This entry is similar to the other ones that concatenate sequences generated from the input and find the length... but it's in APL, which can appear confusing even for a small problem like this. I used Dyalog APL, which offers a free educational license.

Code:

⍴⊃⍪⌿⍳¨⎕⎕

From right to left:

  • Each quote-quad ( ) requests input from the user and evaluates it.
  • The each operator ( ¨ ) applies the index generator function ( ) to each of the items in the array to its right.
  • This flattens the resulting array of arrays into one array. The input array is reduced to a flat list by the reduction operator ( / ), which folds the array using the concatenation function ( , ). For the sake of this challenge, the one-dimensional reduction operator ( ) is used, along with the concatenation operator along the first axis ( ).
  • As a result of using the reduction operator, the array is enclosed, which is like placing it in the bag; all we see on the outside is a bag, not its contents. The disclose operator ( ) gives us the contents of the enclosed array (the bag).
  • Finally, the shape-of function ( ) gives us the lengths of the dimensions of an array. In this case, we have a one-dimensional array, so we obtain the number of items in the array, which is our result.

If we need to explicitly output the result, we can do so like this:

⎕←⍴⊃⍪⌿⍳¨⎕⎕

Comparable Python code, with corresponding APL symbols above:

import operator

⎕←     ⍴    ⌿        ⍪                 ¨              ⍳                ⎕        ⎕         ⊃
print (len (reduce (operator.__add__, [map (lambda n: range (1, n+1), [input(), input()])][0])))

I'd like to know if there's a shorter version possible in APL - another, simpler version I came up with that has more tie breakers (although still at 8 characters) is: ⍴(⍳⎕),⍳⎕.

Dillon Cower

Posted 2011-11-30T23:09:47.133

Reputation: 2 192

Does your index generator start at 1 or 0? – MrZander – 2012-08-17T18:33:10.640

3

I didn't see anyone do it the Electrical Engineering way, so here's my take (in ruby):

def please_sum(a, b)
    return (a&b !=0)? please_sum( ((a&b)<<1) , a^b ):a^b
end

It is a little bit ugly, but it gets the job done. The two values are compared by a bitwise AND. If they don't have any bits in common, there is no "carry" into the next binary column, so the addition can be completed by bitwise XORing them. If there is a carry, you have to add the carry to the bitwise XOR. Here's a little ruby script I used to make sure my digital logic was not too rusty:

100.times do
    a=rand 10
    b=rand 10
    c=please_sum(a,b)
    puts "#{a}+#{b}=#{c}"
    end

Cheers!

Noah

Posted 2011-11-30T23:09:47.133

Reputation: 131

2

Shell, 52

read a
read b
(seq 1 $a;seq 1 $b)|wc|awk '{print$1}'

This is basically the same answer I gave for another problem.

Joey Adams

Posted 2011-11-30T23:09:47.133

Reputation: 9 929

+/- and above mentioned tie-breakers are interesting, not characters. – user unknown – 2012-05-30T03:38:11.263

Similar: xargs -n1 jot | wc -l which takes the same - reduction awk but I can't see how to avoid it in the xargs – Ben Jackson – 2011-12-01T20:12:33.580

2

Javascript (17 tie-breaker characters)

eval('걢갽거걲걯걭거건갨걡갽거걲걯걭거건갨걹갽걦걵걮걣건걩걯걮갨걡갩걻걣갽걮걥걷갠걕걩걮건갸걁걲걲걡걹갨걡갩갻걦걯걲갨걩갠걩걮갠걣갩걩걦갨걩갽갽걾걾걩갩걸갮거걵걳걨갨갱갩걽갬걸갽걛걝갩갩갻걹갨걡갩갻걹갨걢갩갻걡걬걥걲건갨걸갮걬걥걮걧건걨갩갻'['split']('')['map'](function(_){return String['fromCharCode'](_['charCodeAt'](~~[])^0xac00)})['join'](''))

:P ("Obfuscated" to reduce number of tie-breaker characters. Internally, it's b=prompt(a=prompt(y=function(a){c=new Uint8Array(a);for(i in c)if(i==~~i)x.push(1)},x=[]));y(a);y(b);alert(x.length); .)

JiminP

Posted 2011-11-30T23:09:47.133

Reputation: 3 264

2

C

a,b;A(int a,int b){return a&b?A(a^b,(a&b)<<1):a^b;}
main(){scanf("%d%d",&a,&b);printf("%d\n",A(a,b));}

saeedn

Posted 2011-11-30T23:09:47.133

Reputation: 1 241

I count 20 tie breakers... Am I right? – FUZxxl – 2011-12-01T11:11:45.247

222 tie breakers: 0 /*=., 7 (, 7 ), 7 ,, 1 [0-9] – saeedn – 2011-12-01T12:23:07.437

2

C#

It's not the shortest by any stretch:

private static int getIntFromBitArray(BitArray bitArray)
{
    int[] array = new int[1];
    bitArray.CopyTo(array, 0);
    return array[0];
}

private static BitArray getBitArrayFromInt32(Int32 a)
{
    byte[] bytes = BitConverter.GetBytes(a);
    return new BitArray(bytes);
}

static void Main(string[] args)
{
    BitArray first = getBitArrayFromInt32(int.Parse(Console.ReadLine()));
    BitArray second = getBitArrayFromInt32(int.Parse(Console.ReadLine()));
    BitArray result = new BitArray(32);

    bool carry = false;
    for (int i = 0; i < result.Length; i++)
    {
        if (first[i] && second[i] && carry)
        {
            result[i] = true;
        }
        else if (first[i] && second[i])
        {
            result[i] = false;
            carry = true;
        }
        else if (carry && (first[i] || second[i]))
        {
            result[i] = false;
            carry = true;
        }
        else
        {
            result[i] = carry || first[i] || second[i];
            carry = false;
        }
    }
    Console.WriteLine(getIntFromBitArray(result));
}

Matthew Steeples

Posted 2011-11-30T23:09:47.133

Reputation: 131

That's exhausting, Matthew. – Cary Swoveland – 2013-09-25T02:44:42.767

2

J, 15 7 chars, 1 tie breaker, incomplete program

This is my J attempt. It is not a full program, because I have not yet figured out how to write one. Just put that line in a script to get the function p that can be used for adding an arbitrary amount of numbers. It is a monad and takes a list of numbers to add (such as p 1 2 3 4):

p=:#@#~

The idea is very simple. The function is written in tacit aka pointless style. Here is a pointed definition:

p=:3 :'##~y'

Read from right to left. In the tacit version, @ composes the parts of the function. (like a ∘ in mathematics [(f∘g)(x) = f(g(x)])

  • y is the parameter of p.
  • ~ makes a verb reflexive. For some verb m, m~ a is equal to a m a.
  • # (copy, a#b): Each element in a is replicated i times, where i is the element at the same index as the current element of a of b. Thus, #~ replicates an item n n times.
  • # (count, #b): Counts the number of elements in b.

Conclusion: J is awsome and less readable than Perl (that makes it even more awsome)

Edits

  • 15 -> 7 using # instead of i.. Yeah! Less chars than golfscript.

More of a program

This one queries for input, but it still isn't a full program: (13 chars, 3 breakers)

##~".1!:1<#a:

FUZxxl

Posted 2011-11-30T23:09:47.133

Reputation: 9 656

J is definitely awesome, but believe me, you can't just leave out the parsing part of the problem when you solve challenges with it ;-) – J B – 2011-12-01T15:35:12.187

@J B Well, you can use the builtin function toJ, but I keep getting domain errors. – FUZxxl – 2011-12-01T16:54:49.537

2

C#,

Program works on 1 line; separated on multiple lines to avoid horizontal scrolling.

using C=System.Console;
class A{
static void Main(){
int a,b,x,y;
a=int.Parse(C.ReadLine());
b=int.Parse(C.ReadLine());
do{x=a&b;y=a^b;a=x<<1;b=y;}while(x>0);
C.WriteLine(y);
}}

sirchristian

Posted 2011-11-30T23:09:47.133

Reputation: 171

1

Keg (SBCS on Keg wiki)

Basically a port of the R answer.

¿¿Ï_"Ï_!.

Explanation

¿¿#        Take 2 integer inputs
  Ï_"Ï_#   Generate 2 arrays the length of the integer inputs
       !.# Output the length of the stack

user85052

Posted 2011-11-30T23:09:47.133

Reputation:

1

PowerShell, 27 42 bytes, 0 +-, 4 1 secondary

Thanks to mazzy for saving a + and 4 secondaries

$args|%{[int[]]$_*$_}|measure|select count

Try it online! or Pretty Table for an extra 3 bytes

-Or- adding four secondaries to save 19 bytes:

32 23 bytes, 1 0 +-, 12 5 secondaries

-9 bytes thanks to mazzy

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

Try it online!

For each argument, we push n array elements (consisting of [n] but that's not important) to the pipeline which are grouped by the parens and then counted.

Veskah

Posted 2011-11-30T23:09:47.133

Reputation: 3 580

123 bytes, 0 +-, 5 secondaries – mazzy – 2019-09-19T16:13:16.957

1

I'm sorry, this is NOT codegolf. 0 +-, 3 secondries, 27 bytes

– mazzy – 2019-09-19T16:28:16.137

1@mazzy That's 4 by my count but thanks nonetheless :D – Veskah – 2019-09-19T16:34:04.877

1

you are right. thanks. 0+-, 1 Tie Breaker, 42 bytes. you could add |fl for a pretty format Try it online!

– mazzy – 2019-09-19T17:23:40.393

1

05AB1E, 2 4 bytes, 0 +/-

F>

Try it online!

Apologies if I misunderstood this challenge, but I was surprised there was no 05AB1E answer. Shortest answer in this language I could come up with that doesn't use + or the built in sum function.

Explanation:

 F   #Loop A many times
  >  #Increment B
     #(Implicit output)

-2 Bytes thanks to Grimy.

Bismarck71

Posted 2011-11-30T23:09:47.133

Reputation: 41

1Thanks! I'm still new to 05AB1E. – Bismarck71 – 2019-09-25T07:30:15.450

1

Python 3

Without relying on hidden summations in other functions.

h=input;x,y=int(h()),int(h())
while y:c=x&y;x^=y;y=c<<1
print(x)

Try it online!

Hunaphu

Posted 2011-11-30T23:09:47.133

Reputation: 121

1

Clojure (44 chars)

(pr(#(count(concat(%)(%)))#(repeat(read)0)))

Edit: fixed to print on STDOUT instead of just returning sum.

Omar

Posted 2011-11-30T23:09:47.133

Reputation: 1 154

+/- and above mentioned tie-breakers are interesting, not characters. – user unknown – 2012-05-30T03:39:09.080

1

Scala

  • score:
    • +- : 0
    • (). : 5+5+3=13

Code:

(List.fill (readInt) (1) ::: List.fill (readInt) (2)).size
  • List.fill (4)(7) produces List (7, 7, 7, 7)
  • a ::: b concatenates 2 Lists into one
  • The rest should be obvious

user unknown

Posted 2011-11-30T23:09:47.133

Reputation: 4 210

1

K, 11

{#,[!x;!y]}

Same concatenation trick as the R solution. Reading right to left: Enumerate the two input variables, concatenate and then count.

tmartin

Posted 2011-11-30T23:09:47.133

Reputation: 3 917

0

R, 44 bytes

nchar(paste(strrep(" ",scan()),collapse=""))

Try it online!

Converts the two inputs to unary and "sums" via concatenation. Check out the other R answers:

JayCe

Posted 2011-11-30T23:09:47.133

Reputation: 2 655

0

C, score 0 with 8 tie-breakers

f(a,b) { return b ? f(a^b, a<<1 & b<<1) : a; }
 ^ ^ ^               ^   ^    ^      ^^

I've highlighted the tie-break chars.

Negative numbers are assumed to be 2s-complement.

Toby Speight

Posted 2011-11-30T23:09:47.133

Reputation: 5 058

0

Javascript (ES6) - 8 Tie-breaker characters

add: {
    let a = prompt``|false;
    let b = prompt``|false;
    while (a & b) {
        a = a ^ b;
        b = [b & ~a][false|false] << true
    }
    alert(a | b);
}
  • 2 * (
  • 2 * )
  • 4 * =

Sasha

Posted 2011-11-30T23:09:47.133

Reputation: 431

0

Gol><>, 12 bytes

IITM:{P}?trh

Thanks to JoKing for reminding me there was a Teleport Pad!!

1st version, 25 bytes

II!/M:{P}?\rh
   \     :/

Try it online!

This was alot easier than I thought it would be!!! I will be golfing this alot more!!!

KrystosTheOverlord

Posted 2011-11-30T23:09:47.133

Reputation: 681

12 bytes using teleports, 10 bytes using put. Or 13 bytes without tie breaker characters – Jo King – 2019-02-10T03:02:56.877

@JoKing Wow. Those use strategies I wasn't even thinking of!!!, nice! – KrystosTheOverlord – 2019-02-10T03:44:42.080

0

Runic Enchantments, (no +/-, 1 tie-breaker, 11 bytes)

'V2,k!$wi|;

Try it online!

Not allowed to have + characters? Fine, I'll create them myself with math and reflection. V has the byte value 86, which gets divided by 2 (the , and only tie-breaker character) converted to a character, and finally, reflectively written into the program under the instruction pointer. It then reads input, hits a reflector (|), reads input again, then reaches the space originally containing a w and adds them together before printing. The IP then performs an illegal action at , and is silently terminated.

Is this cheating? Probably. But the challenge says "don't use + characters" and the source code contains 0 of them.

Alternate method, (no +/-, 3 tie-breakers, 16 bytes)

"ab"1,i*}i*qul$;

Try it online!

Makes two strings, one of length x and one of length y, concatenates them together, then computes the length of the string. Does this count as a "sum-like function"? Perhaps. + on two strings does do the same thing.

Draco18s no longer trusts SE

Posted 2011-11-30T23:09:47.133

Reputation: 3 053

0

APL (Dyalog Unicode), 4 bytesSBCS, 0 +/-, 0 tie breakers

Can sum any number of non-negative integers.

≢⎕⌿#

Try it online!

# reference to the root object

⎕/ replicate by the number(s) from STDIN
for each number, we get that many copies of the corresponding element on the right, but since there is only one, all numbers get paired up with that one, forming a single list of N1+N2+…+Nn references

 tally

Output is implicitly to STDOUT.

Adám

Posted 2011-11-30T23:09:47.133

Reputation: 37 779

0

Befunge-98 (FBBI), 4 bytes, one +.

&&+.

Try it online!

Krzysztof Szewczyk

Posted 2011-11-30T23:09:47.133

Reputation: 3 819

Surely you could use p to place a + command? – negative seven – 2019-09-19T15:30:37.497

@negativeseven I just made it for my Seed answer below. – Krzysztof Szewczyk – 2019-09-19T15:31:35.203

0

MathGolf, 3 bytes, 0 +/-

α▓∞

Try it online!

While perhaps violating the spirit of the "no sum" rule, this solution wraps the inputs into an array, calculates the average of the values in that array, and duplicates the result. Of course, the avg operator uses a sum internally, but its behavior is inherently different compared to the sum operator Σ.

The output is printed as a float, with .0 at the end. If this is not acceptable, just add i to the end to convert it back into an integer.

Explanation

α     wrap last two elements in array
 ▓    get average of list
  ∞   pop a, push 2*a

maxb

Posted 2011-11-30T23:09:47.133

Reputation: 5 754

0

Befunge-98 (PyFunge), 0 +/- characters, 0 tiebreaker characters, 47 bytes

brqzzzzzzzzzzzzzzzzzzzpyadgyacpyappyacybyabybay

Try it online!

Made all out letters, because why not?

More readable variant that does pretty much the same thing:

b<@                               &&pyapyabybay

Abuses the y GetSysInfo command, which can be used to retrieve the instruction pointer's current X coordinate. This is used to push the ASCII codes for + (add) and . (output), which later get put onto the field.

negative seven

Posted 2011-11-30T23:09:47.133

Reputation: 1 931

0

Ruby -na0, no +/-, no tiebreakers, 60 bytes

$F<<?a until~%r[
]&&$F::join[%r[a{#$`}a{#$'}]]
p$F::count ?a

Try it online!

Actually harder than I thought, I'm almost certainly missing a trick.

Reads in the input, then adds a characters to the argument array until the array, when joined into a string, matches a regular expression that uses the two input numbers as quantifiers, then counts how many it added.

Syntax tricks include using %r[] instead of // for a regexp, and :: instead . for a method call.

histocrat

Posted 2011-11-30T23:09:47.133

Reputation: 20 600

0

Zsh, 26 bytes, 7 tiebreakers

Positional parameters are pretty punishing

x=({1..$1} {1..$2})
<<<$#x

Try it online!


62 bytes, 0 tiebreakers

read a b
{repeat $a;printf x;repeat $b;printf x}|read x
<<<$#x

Try it online!

GammaFunction

Posted 2011-11-30T23:09:47.133

Reputation: 2 838

0

C++, () only for main

#include <iostream>

int main()
{
    unsigned int a, b;
    std::cin >> a;
    std::cin >> b;


    unsigned int p = a ^ b;
    unsigned int g = a & b;

    unsigned int gg {g | p & g << 1};
    unsigned int pp {p & p << 1};

    unsigned int ggg {gg | pp & gg << 2};
    unsigned int ppp {pp | pp << 2};

    unsigned int gggg {ggg | ppp & ggg << 4};
    unsigned int pppp {ppp & ppp << 4};

    unsigned int ggggg {gggg | pppp & gggg << 8};
    unsigned int ppppp {pppp | pppp << 8};

    unsigned int gggggg {ggggg | ppppp & ggggg << 16};

    unsigned int result {a ^ b ^ gggggg << 1};
    std::cout << result;
}

Assumes 32-bit unsigned ints. Very ugly code to remove tiebreak characters. Emulates a Kogge-Stone adder.

me'

Posted 2011-11-30T23:09:47.133

Reputation: 451

0

Octave/MATLAB, 37 bytes

f=@()e^(input(''));disp(log(f()*f()))

Try it online!

Hunaphu

Posted 2011-11-30T23:09:47.133

Reputation: 121

1Welcome to the site! I'd recommend you split these up into two answers so that users can vote and improve them separately. – caird coinheringaahing – 2019-09-20T14:49:39.517

0

Python 3

import numpy as n;i=lambda:n.e**int(input());print(int(n.log(i()*i())))

Try it online!

Hunaphu

Posted 2011-11-30T23:09:47.133

Reputation: 121

1I was trying to remove the log and e but forgot about the original restrictions... :( Reverted now. – Hunaphu – 2019-09-20T15:12:47.783

Okay it's working now. You should probably include the link in your answer: Try it online!

– Grimmy – 2019-09-20T15:13:47.723

Welcome! Please consider adding an explanation or a link to an online interpreter. Code-only answers tend to be automatically flagged as low-quality. – mbomb007 – 2019-09-20T15:43:39.623

0

Ruby, 0 +/-, 0 tie-breakers, 39 bytes

And fairly unreadable.

p"#{"%#{"%ss%%%ss"%$F}"%%w[o o]}"::size

Try it online!

Reinstate Monica -- notmaynard

Posted 2011-11-30T23:09:47.133

Reputation: 1 053

0

Gol><>, 8 bytes

IRmIRmlh

Minus one byte!, I figured out that I didn't need to take both inputs first

Try it online!

Previous answer, 9 bytes

IIRfrRflh

Explanation below

II        take both inputs
  Rm      Pop and repeat that number of times, pushing -1
    r     Reverse stack (to get the first num on top)
     Rm   Pop and repeat that number of times, pushing -1
       lh Push length of stack, and output as a number halting

Basically what I did was count it all out in unary, it would only take a few more bytes to expand it to be able to handle more than two numbers

Try it online!

KrystosTheOverlord

Posted 2011-11-30T23:09:47.133

Reputation: 681

0

JavaScript (ES6), 48 bytes, 12 tie-breakers

a=>b=>"0".repeat(a).concat("0".repeat(b)).length

Naruyoko

Posted 2011-11-30T23:09:47.133

Reputation: 459

0

C#, 12 tiebreakers (), 3 tiebreakers .

using System;
using System.Data;

class Program {
  static string ReadLine { get { return Console.ReadLine(); } }
  static void Main(string[] args) {
    Console.Out.Write(
     new DataTable().Compute(string.Join("\u002b", 
     ReadLine,
     ReadLine), "")
    );
  }
}

Ondrej Svejdar

Posted 2011-11-30T23:09:47.133

Reputation: 119

0

JavaScript 69

My attempt, using bitwise operators

for(x=(z=prompt().split(" "))[0],y=z[1];y;)x^=y,y=(y&x^y)<<1;alert(x)

WallyWest

Posted 2011-11-30T23:09:47.133

Reputation: 6 949

0

D

main(){
    int a,b;
    readf("%d %d",&a,&b);
    write((new int[a]~new int[b]).length);
}

this time using array lengths

ratchet freak

Posted 2011-11-30T23:09:47.133

Reputation: 1 334

0

Python

i=input
print eval('%d\x2b%d'%(i(),i()))

37 chars with a little bit of cheating :p

fortran

Posted 2011-11-30T23:09:47.133

Reputation: 101

0

A very yucky C version

Has no +, -, / or any digits. One use of * for a pointer type. The others (()=,) are needed a lot in the language itself.

#include <malloc.h>
#include <string.h>
#include <stdio.h>
typedef unsigned char *ptr;

char
  y;

const size_t
  one = sizeof y;

unsigned char
  zero='a'^'a',
  a [] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  z [] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  x [] = "xxxxxxxxxxxxxxxxx";

size_t plus_one (size_t i)
{
  ptr b=&a[one];
  memset (a,'x',sizeof a);
  b[i]=zero;
  return strlen(a);
}

size_t minus_one (size_t i)
{
  ptr b=&a[one];
  memset (a,'x',sizeof a);
  a[i]=zero;
  return strlen(b);
}

size_t minus_zero (size_t i)
{
  size_t p;
  for (p = zero ; z[p] ; p = plus_one (p))
  {
    i = minus_one(i);
  }
  return i;
}

unsigned char to_zero (unsigned char i)
{
  size_t p;
  for (p = one>>one ; x[p] ; p = plus_one (p))
  {
    i = (unsigned char) minus_one(i);
  }
  return i;
}

main (int argc, ptr argv [])
{
  ptr
    a = argv [argc>>one],
    b = argv [argc>>one<<one];

  size_t
    len_a = strlen (a),
    len_b = strlen (b),
    len = len_a > len_b ? len_a : len_b,
    o = plus_one(len),
    i,
    c=one>>one;

  ptr
    res=(ptr)malloc(plus_one(o));

  res[o]=zero;

  for (i = zero ; i < len ; i=plus_one(i))
  {
    size_t va;
    unsigned char r;

    va = (len_a > zero ? minus_zero (a[minus_one(len_a)]) <<one<<one<<one<<one : zero) | (len_b > zero ? minus_zero (b[minus_one (len_b)]) : zero);
    r = (c?"bcdefghijAuhjsadcdefghijABsadlkfdefghijABCvsxwerefghijABCDDNIWjsfghijABCDEOQJdccghijABCDEFIndDjlhijABCDEFGCnjndwijABCDEFGHsadXSkjABCDEFGHICSjshdABCDEFGHIJcbaCBA":"abcdefghijaswhHDbcdefghijAQWuciucdefghijABCOasdpdefghijABCCnjaskefghijABCDCIUdasfghijABCDEuoiDSAghijABCDEFCsalkjhijABCDEFGcapCPcijABCDEFGHCWEoerjABCDEFGHIkjIjIj") [va];
    c=r<'a';
    r&=~(one<<one<<one<<one<<one<<one);
    o=minus_one(o);
    res[o]=to_zero(r);

    if (len_a) len_a = minus_one (len_a);
    if (len_b) len_b = minus_one (len_b);
  }
  if(c) 
  {
    o=minus_one(o);
    res[o]=to_zero('B');
  }
  printf("%s\n",&res[o]);
  free (res);
}

Skizz

Posted 2011-11-30T23:09:47.133

Reputation: 2 225

0

Common Lisp

Always surprising for such a verbose language.

((lambda(n m)(princ(length(append(make-list n)(make-list m)))))(read)(read))

Joanis

Posted 2011-11-30T23:09:47.133

Reputation: 291

0

VBA - No +/-, 7 tie-breakers

+,-,/,*,,,.,0-9 = 0
( = 3 (3 total pairs)
) = 3
= = 1

Function a(b)
    For Each c In b
        a = a & Space(c)
    Next
    MsgBox Len(a)
End Function

Takes an array of natural numbers as an argument. This will actually add more than just 2 values, if provided, as well as return the value of a single argument.

Older versions


+,-,/,*,=,.,0-9 = 0
( = 4 (4 total pairs)
) = 4
, = 1

Function a(b, c)
MsgBox Len(Space(b) & Space(c))
End Function

+,-,/,*,=,.,0-9 = 0
( = 4 (4 total pairs)
) = 4
, = 3

Sub a(b,c)
MsgBox Len(String(b," ") & String(c," "))
End Sub

+,-,/,*,. = 0
= = 4
( = 2 (2 total pairs)
) = 2
0-9 = 2
, = 1

Sub d(e,f)
For g=1 To e:h=h & " ":Next
For g=1 To f:h=h & " ":Next
MsgBox Len(h)
End Sub

Gaffi

Posted 2011-11-30T23:09:47.133

Reputation: 3 411

Character count technically doesn't matter in this challenge. You have no -+, and you have 11 tie breakers. This puts you above any solution that has a -+ character, and below any solution with no -+ with fewer tie breakers. – PhiNotPi – 2012-04-12T15:43:11.673

So, I am tied with (as one example) Uri Goren's answer, correct? He has no +/-, but 11 tie-breakers.

– Gaffi – 2012-04-12T15:45:38.797

Yes, you are tied with him. – PhiNotPi – 2012-04-12T15:50:45.440

0

C #, 26 tiebreakers

+/- : 0
=   : 2
.   : 6 
()  : 18
using System;
using System.Linq;
class P
{
    static void Main()
    {
        Func<int[]> f=()=>new int[int.Parse(Console.ReadLine())];
        Console.Write(f().Concat(f()).Count());
    }
}

mizer

Posted 2011-11-30T23:09:47.133

Reputation: 311

0

PHP, 22 chars

echo array_sum($argv);

Documentation: array_sum() and $argv
Usage: php -r 'echo array_sum($argv);' 5 6 will output 11.

powtac

Posted 2011-11-30T23:09:47.133

Reputation: 893

+/- and above mentioned tiebreakers are interesting, not chars. – user unknown – 2012-05-30T03:35:04.780

0

APL (10, 3 tie-breakers)

⎕←⍴(⍳⎕),⍳⎕

marinus

Posted 2011-11-30T23:09:47.133

Reputation: 30 224

10x +/-? Chars arn't interesting, just +/- and the tie-breakers. – user unknown – 2012-05-30T03:34:11.410

0

Python 3 - 159 characters | ().,*/= count: 39

A little long, but I felt like doing it HDL-style.

a,b,c,d=int(input()),int(input()),0,0;l=max(a,b,key=int.bit_length)
for i in range(len(bin(l<<1)[2:])):
 e=a>>i&1;f=b>>i&1;c|=(e^f^d)<<i;d=e&f|d&(e^f)
print(c)

JAB

Posted 2011-11-30T23:09:47.133

Reputation: 181

+/- tiebreakers are interesting, not characters. – user unknown – 2012-05-30T03:33:22.473

@userunknown: What's wrong with characters? – JAB – 2012-05-30T16:55:31.163

Characters are counted in CodeGolf tagged questions. If a reader doesn't read the question again, he will get the impression that character count is important and probably make a misguided vote based on that assumption. So the rules say: No (+|-). In Tiebreak digits, ().,*/= are important. You should include that number in your answer, so that not every visitor has to count them himself. – user unknown – 2012-05-30T20:41:48.303

@userunknown: Oh, right. – JAB – 2012-05-30T20:46:42.957

0

C# 141 characters 27 tiebreakers

+/- : 0
=   : 0
.   : 9 
()  : 18


Console.WriteLine(Enumerable.Range(1,int.Parse(Console.ReadLine()))
.Concat(Enumerable.Range(1,int.Parse(Console.ReadLine())))
.Count());

hermiod

Posted 2011-11-30T23:09:47.133

Reputation: 321

0

Python 42

a,b=input()
print eval("~-"*a+"~-"*b+"0")

Seven tie breakers, but those are string operations

walpen

Posted 2011-11-30T23:09:47.133

Reputation: 3 237