29
\$\begingroup\$

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.

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Perhaps 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. \$\endgroup\$
    – PhiNotPi
    Commented Dec 1, 2011 at 0:45
  • 3
    \$\begingroup\$ Just 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 :-) \$\endgroup\$
    – Tommy
    Commented Dec 1, 2011 at 19:39
  • \$\begingroup\$ @Tommy No, it does not. \$\endgroup\$
    – PhiNotPi
    Commented Dec 1, 2011 at 21:58
  • 2
    \$\begingroup\$ Are languages allowed that don't have arithmetic operators at all? I think that last sentence permits them, but it's not completely clear. \$\endgroup\$ Commented Aug 1, 2018 at 15:39
  • 2
    \$\begingroup\$ Next challenge would be "Comparing two numbers without any of ><+-*/%&|" \$\endgroup\$
    – Naruyoko
    Commented Sep 19, 2019 at 23:41

75 Answers 75

54
\$\begingroup\$

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
\$\endgroup\$
5
  • 1
    \$\begingroup\$ Very clever, good job. \$\endgroup\$ Commented Dec 1, 2011 at 21:34
  • 1
    \$\begingroup\$ This blows my mind \$\endgroup\$
    – smci
    Commented Jan 21, 2012 at 9:25
  • \$\begingroup\$ +/- and above mentioned tie-breakers are interesting, not characters. \$\endgroup\$ Commented May 30, 2012 at 3:36
  • \$\begingroup\$ How does it calculate length? without using any addition? If so, I'd be surprised. \$\endgroup\$
    – Tem Pora
    Commented Sep 28, 2013 at 10:12
  • 4
    \$\begingroup\$ @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. \$\endgroup\$
    – mbomb007
    Commented Jul 31, 2018 at 14:57
37
\$\begingroup\$

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

\$\endgroup\$
4
  • 4
    \$\begingroup\$ +1 - awsome and totally unreadable ;-) This seems to be the perfect answer since the character count doesn't matter in this challenge. \$\endgroup\$
    – Tommy
    Commented Dec 1, 2011 at 22:14
  • 2
    \$\begingroup\$ @Tommy, there are other perfect answers too. Maybe we should push for character count to be the final tie-breaker. \$\endgroup\$ Commented Dec 2, 2011 at 17:04
  • \$\begingroup\$ @Peter: I sort of assumed it already was, by default. \$\endgroup\$ Commented Dec 2, 2011 at 17:19
  • 2
    \$\begingroup\$ if 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? \$\endgroup\$
    – Sparr
    Commented Sep 19, 2019 at 23:26
18
\$\begingroup\$

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)

\$\endgroup\$
13
\$\begingroup\$

Python 2, 43 bytes

print len('%s%s'%(input()*'?',input()*'!'))
\$\endgroup\$
4
  • 4
    \$\begingroup\$ Very inventive, but you might want to change the character used in the string to something other than a tie-breaker such as "~" \$\endgroup\$
    – 3Doubloons
    Commented Dec 1, 2011 at 5:36
  • \$\begingroup\$ Thanks for the advice Alex, I had already forgotten about the tie-breaker rule. \$\endgroup\$
    – Omar
    Commented Dec 2, 2011 at 17:38
  • \$\begingroup\$ print sum(input(),input()) \$\endgroup\$
    – razpeitia
    Commented Dec 3, 2011 at 2:52
  • 18
    \$\begingroup\$ razpeitia: I think sum is a "sum-like" function and thus not allowed. \$\endgroup\$
    – Omar
    Commented Dec 3, 2011 at 12:38
10
\$\begingroup\$

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

4 141745954
\$\endgroup\$
1
  • \$\begingroup\$ Next up: the self-hosted version of seed LOL!! \$\endgroup\$
    – Dagelf
    Commented May 13, 2021 at 22:45
8
\$\begingroup\$

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)

\$\endgroup\$
0
8
\$\begingroup\$

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

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.

\$\endgroup\$
0
6
\$\begingroup\$

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.

\$\endgroup\$
0
6
\$\begingroup\$

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!

\$\endgroup\$
5
\$\begingroup\$

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
\$\endgroup\$
3
  • 1
    \$\begingroup\$ +1 For making me have to change the rules to outlaw the sum() function. \$\endgroup\$
    – PhiNotPi
    Commented Dec 1, 2011 at 0:48
  • 1
    \$\begingroup\$ @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... \$\endgroup\$
    – Tommy
    Commented Dec 1, 2011 at 0:53
  • 3
    \$\begingroup\$ I'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. \$\endgroup\$
    – PhiNotPi
    Commented Dec 1, 2011 at 0:59
5
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ 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. \$\endgroup\$
    – PhiNotPi
    Commented Dec 1, 2011 at 1:14
  • \$\begingroup\$ +1 Nice. You can make this even shorter with scan() instead of readlines(n=2) \$\endgroup\$
    – Andrie
    Commented Dec 1, 2011 at 21:53
  • \$\begingroup\$ @Andrie - yes, but then you rely on the user entering exactly two numbers... Which is OK for this challenge I guess... \$\endgroup\$
    – Tommy
    Commented Dec 1, 2011 at 22:07
5
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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" \$\endgroup\$
    – Omar
    Commented Dec 7, 2011 at 0:06
5
\$\begingroup\$

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.

\$\endgroup\$
0
5
\$\begingroup\$

Excel, (25, 8) (22, 6) 13, 4 tie-breakers

Inputs are A1, A2.

=2*MEDIAN(A:A
^^^      ^

Because MEDIAN is shorter than AVERAGE and AGGREGATE.

\$\endgroup\$
5
\$\begingroup\$

Python 3, 64 62 bytes

Without relying on hidden summations in other functions.

x=int(input());y=int(input())
while y:x,y=x^y,(x&y)*2
print(x)

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ by replacing the first line by x=int(input());y=int(input()) you save 2 tie breakers (and without loosing any byte). You should also redo your TIO link, to make it mach your post \$\endgroup\$
    – Jakque
    Commented May 11, 2021 at 10:42
4
\$\begingroup\$

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)
\$\endgroup\$
4
  • \$\begingroup\$ That space after the comma is completely unnecessary; removing it gets you down to 81. \$\endgroup\$ Commented Dec 2, 2011 at 23:53
  • \$\begingroup\$ 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... \$\endgroup\$
    – JiminP
    Commented Dec 3, 2011 at 0:29
  • 1
    \$\begingroup\$ Oh, 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. \$\endgroup\$
    – JiminP
    Commented Dec 4, 2011 at 14:14
  • \$\begingroup\$ ES6 version: _=>Array(~~prompt``)["concat"](Array(~~prompt``))["length"] with 7 TB \$\endgroup\$ Commented Aug 2, 2020 at 14:26
4
\$\begingroup\$

C

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

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

\$\endgroup\$
1
  • \$\begingroup\$ Clever use of obfuscation! Love it! \$\endgroup\$
    – Seth
    Commented Mar 6, 2021 at 17:11
4
\$\begingroup\$

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: ⍴(⍳⎕),⍳⎕.

\$\endgroup\$
1
  • \$\begingroup\$ Does your index generator start at 1 or 0? \$\endgroup\$
    – MrZander
    Commented Aug 17, 2012 at 18:33
4
\$\begingroup\$

Befunge-93, 0 +- characters, 0 tiebreakers, 33 bytes

"e:"%"X:"%::%p"h:"%"Y:"%::%p&&  @

Try it online!

Explanation

Like @negative seven's Befunge answer, we generate + and . at runtime and put them onto the field to be executed. However, Befunge-93 does not include the y instruction, so we abuse the % modulo operator instead.

"e:"%                                            # Calculate 101 ('e') mod 58 (':') to get 43 ('+')
     "X:"%                                       # Calculate 88 ('X') mod 58 to get 30
          ::%                                    # Calculate 30 mod 30 to get 0
             p                                   # Put character 43 ('+') at position (30, 0)
              "h:"%                              # Calculate 104 ('h') mod 58 to get 46 ('.')
                   "Y:"%                         # Calculate 89 ('Y') mod 58 to get 31
                        ::%                      # Calculate 31 mod 31 to get 0
                           p                     # Put character 46 ('.') at position (31, 0)
                            &&                   # Get two numbers from STDIN
                              (changed to '+')   # Add the numbers together
                               (changed to '.')  # Output the result
                                @                # End the program
\$\endgroup\$
4
\$\begingroup\$

Scala 2.12, 20 bytes, 0 +/- signs

readInt\u002breadInt

The unicode literal is just turned into a + before compilation

\$\endgroup\$
1
  • 2
    \$\begingroup\$ This is in no way cheating. In fact, this answer emphasizes the very reason why "do X without Y" is now discouraged. \$\endgroup\$ Commented Jul 30, 2020 at 0:10
4
\$\begingroup\$

Vyxal as, 0 bytes

Try it Online!

The a flag takes newline separated inputs as a list, and the s flag sums the top of the stack.

Non-trivial a, 4 2 bytes

-2 bytes because I realized the challenge guarantees 2 number input.

ṁd

Try it Online!

Explanation:

    # 'a' flag - take newline separated inputs as a list
ṁ   # Mean of inputs
 d  # Multiply by 2
    # Implicit output

Effectively calculates ((a + b) / 2) * 2, which is equivalent to a + b. The previous version worked for any amount of numbers, but it turns out the challenge specifies taking 2 numbers as input, so this works fine.

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

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.

\$\endgroup\$
2
  • \$\begingroup\$ Similar: xargs -n1 jot | wc -l which takes the same - reduction awk but I can't see how to avoid it in the xargs \$\endgroup\$ Commented Dec 1, 2011 at 20:12
  • \$\begingroup\$ +/- and above mentioned tie-breakers are interesting, not characters. \$\endgroup\$ Commented May 30, 2012 at 3:38
2
\$\begingroup\$

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));}
\$\endgroup\$
2
  • \$\begingroup\$ I count 20 tie breakers... Am I right? \$\endgroup\$
    – FUZxxl
    Commented Dec 1, 2011 at 11:11
  • 2
    \$\begingroup\$ 22 tie breakers: 0 /*=., 7 (, 7 ), 7 ,, 1 [0-9] \$\endgroup\$
    – saeedn
    Commented Dec 1, 2011 at 12:23
2
\$\begingroup\$

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));
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ That's exhausting, Matthew. \$\endgroup\$ Commented Sep 25, 2013 at 2:44
  • \$\begingroup\$ Is this a literal full adder circuit implemented in a program? \$\endgroup\$
    – Seggan
    Commented May 2, 2022 at 21:05
2
\$\begingroup\$

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:
\$\endgroup\$
2
  • \$\begingroup\$ 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 ;-) \$\endgroup\$
    – J B
    Commented Dec 1, 2011 at 15:35
  • \$\begingroup\$ @J B Well, you can use the builtin function toJ, but I keep getting domain errors. \$\endgroup\$
    – FUZxxl
    Commented Dec 1, 2011 at 16:54
2
\$\begingroup\$

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

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.

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

Octave/MATLAB, 37 bytes

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

Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to the site! I'd recommend you split these up into two answers so that users can vote and improve them separately. \$\endgroup\$ Commented Sep 20, 2019 at 14:49
  • \$\begingroup\$ 31 by using the implicit output \$\endgroup\$ Commented Jul 29, 2020 at 23:53
  • \$\begingroup\$ Also, your answer does not actually work in Matlab since it does not have e defined. I believe the shortest answer in Matlab (at least with this approach) is, therefore, 32. \$\endgroup\$ Commented Jul 29, 2020 at 23:54

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