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

The problem:

I am the lead developer for a big company, we are making Skynet. I have been assigned to

Write a function that inputs and returns their sum

RULES: No answers like

function sum(a,b){
    return "their sum";
}

EDIT: The accepted answer will be the one with the most upvotes on January 1st, 2014

Note: This is a question. Please do not take the question and/or answers seriously. More information here.

share|improve this question
20  
You can use my lightweight jQuery plugin: $.sum=function(a,b){return a+b};. –  Blender 2 days ago
4  
I knew I'd get a jQuery reference sometime –  scrblnrd3 2 days ago
4  
Brilliant English :p –  Martijn Courteaux 2 days ago
1  
Question suggestion (not sure if it's any good): "GUISE HALP, I need a fast algorithm to generate bitcoin blocks!!!!! It's super urgent!" –  Shingetsu 2 days ago
4  
These answers are quite involved. I suggest opening a connection to your database and issuing 'SELECT ' + a + ' + ' + b + ';'. It's simple and understandable. –  Nick Chammas 2 days ago
show 8 more comments

64 Answers

That's a very complex problem! Here is how you solve it in C#:

static int Sum(int a, int b)
{
    var aa = ((a & ~877 - b ^ 133 << 3 / a) & ((a - b) - (a - b))) | a;
    var bb = ((b ^ (a < 0 ? b : a)) & ((b - a) - (b - a))) | b;
    var cc = new List<int>();
    for (int i = 6755 & 1436; i < aa; i -= -1)
    {
        cc.Add((int)Convert.ToInt32(Math.Sqrt(6755 & 1437 >> ((b - a) - (b - a)))));
    }
    for (int i = 6755 & 1436; i < bb; i -= -1)
    {
        cc.Add((int)Convert.ToInt32(Math.Sqrt(6755 & 1437 >> ((a - b) - (a - b)))));
    }
    Func<int,int,int> importantCalculation = null;
    importantCalculation = (x, y) => y != 0 ? importantCalculation(x ^ y | (6755 & 1436) >> (int)(Convert.ToInt32(Math.Sqrt((b - a) - (b - a) - (-1))) - 1), (x & y) << (int)Convert.ToInt32((Math.Log10(1) + 1))) : x;
    return cc.Aggregate(importantCalculation);
}


How this code works (I wouldn't add this explanation in my answer to the lazy OP that has to be trolled, don't worry): ((a & ~877 - b ^ 133 << 3 / a) & ((a - b) - (a - b))) | a returns just a and ((b ^ (a < 0 ? b : a)) & ((b - a) - (b - a))) | b returns just b.

6755 & 1436 returns 0, so in the loop, i actually starts with value 0, and inside the loop, you add the value 1 to the list. So, if a is 5 and b is 3, the value 1 is added 8 times to the list.

The importantCalculation function is a very long function that does nothing else than adding up two numbers. You use the LINQ Aggregate function to add up all numbers. It's also unnecessary to cast the result of Convert.ToInt32 to an int, because it is already an int.

This code is something that the lazy OP wouldn't understand, which is exactly the intension :-)

share|improve this answer
6  
i -= -1. Very creative. I already reached the vote limit today, but I will upvote your answer as soon as I can. –  Victor 2 days ago
 
As long as you insist that anything other than 6755 & 1436 is undefined behavior, despite OP's perception that most numbers seem to work... –  trojansdestroy 2 days ago
 
What is the meaning of '=>'? –  Babibu yesterday
1  
@Babibu I have never written a line of C# in my life but this is almost certainly a lambda expression. –  tomwilde yesterday
 
@Babibu: tomwilde is right, it's a lambda expression. –  ProgramFOX yesterday
show 1 more comment

Bash - 72 bytes

Sometimes traditional deterministic addition techniques are too precise, and unnecessarily fast - there are times when you want to give the CPU a bit of a rest.

Introducing the lossy SleepAdd algorithm.

#!/bin/bash
(time (sleep $1;sleep $2)) 2>&1|grep re|cut -dm -f2|tr -d s

Sample run:

> ./sleepadd.sh 0.5 1.5
2.001

This function is intended as a companion to the well-regarded SleepSort. It is left as an exercise to the reader to adapt this algorithm to make a lossy SleepMax to obtain the greater of two numbers.

Pro Tip: This algorithm can be further optimised - a 2x speed increase is possible, if the numbers given to it are divided by 2 first.

share|improve this answer
2  
Trolling 1: it works but it's stupidly slow, using the system timer to wait for the total time. Therefore larger numbers take linearly longer to add. Trolling 2: it even works for floating point, but the answers are always off by a small margin. Trolling 3: gratuitous and unnecessary use of grep, cut and tr. Trolling 4: any totals over 60 (seconds) are not handled correctly. –  Riot 2 days ago
3  
@Shingetsu: what, you're saying nobody else has heard of mp3 codecs? :P –  Riot 2 days ago
5  
I'm saying very few people actually make the association. Lame IS lame though. Vorbis master race. –  Shingetsu 2 days ago
3  
+1 for massively off-topic audio encoder wars diatribe :) –  Riot 2 days ago
1  
I believe my Bash-Hadoop version below is much more powerful and scalable!!!!1!!eleven! But I must say, I really love your version, sleepadd is great! +1 –  Anony-Mousse 2 days ago
show 5 more comments

Java

public static void int sum(int a, int b)
{
    try
    {
       File file = File.createTempFile("summer", "txt");
       FileOutputStream fos = new FileOuptutStream(file);
       for (int i = 0; i < a; ++i) fos.write(1);
       for (int i = 0; i < b; ++i) fos.write(1);
       fos.flush();
       fos.close();
       return file.length();
    } catch(Throwable t)
    {
       return sum(a, b); // Try again!
    }
}

This basically writes a file with the number of bytes that should be equal to the actual sum. When the file is written, it asks the disk file table for the size of that file.

share|improve this answer
1  
Can write or flush throw? It looks to me like you should move flush into each loop, and wrap the whole thing in a try-catch to retry the write if it or the flush fails. –  Anton Golov 2 days ago
1  
I suggest you use a writer with the default character encoding instead of a stream. Then it can potentially break on a system for which your selected character encodes into multiple bytes. –  Buhb yesterday
add comment

Haskell

Computes the correct solution in O(n^2) time. Based on applicative functors that also implement Alternative.

{- Required packages:
 -   bifunctor
 -}
import Control.Applicative
import Data.Foldable
import Data.Traversable
import Data.Bifunctor
import Data.Monoid

-- Note the phantom types
data Poly n a = X n (Poly n a) | Zero
    deriving (Show)

twist :: Poly n a -> Poly n b
twist Zero = Zero
twist (X n k) = X n (twist k)

instance Functor (Poly n) where
    fmap _ = twist
instance Bifunctor Poly where
    second = fmap
    first f Zero    = Zero
    first f (X n k) = X (f n) (first f k)

-- Poly is a left module:
(<#) :: (Num n) => n -> Poly n a -> Poly n a
(<#) = first . (*)

instance (Num n) => Applicative (Poly n) where
    pure _ = X 1 empty
    Zero    <*> _      = empty
    (X n k) <*> q      = (twist $ n <# q) <|> (X 0 (k <*> q))

instance (Num n) => Alternative (Poly n) where
    empty = Zero
    Zero    <|> q       = q
    p       <|> Zero    = p
    (X n p) <|> (X m q) = X (n + m) (p <|> q)

inject :: (Num n) => n -> Poly n a
inject = flip X (X 1 Zero)


extract :: (Num n) => (Poly n a) -> n
extract (X x (X _ Zero)) = x
extract (X _ k)          = extract k
extract _                = 0

-- The desired sum function:
daSum :: (Traversable f, Num n) => f n -> n
daSum = extract . traverse inject

Example: daSum [1,2,3,4,5] yields 15.


Update: How it works: A number a is represented as a polynomial x-a. A list of numbers a1,...,aN is then represented as the expansion of (x-a1)(x-a2)...(x-aN). The sum of the numbers is then the coefficient of the second highest degree. To further obscure the idea, a polynomial is represented as an applicative+alternative functor that doesn't actually hold a value, only encodes the polynomial as a list of numbers (isomorphic to Constant [n]). The applicative operations then correspond to polynomial multiplication and the alternative operations to addition (and they adhere to applicative/alternative laws as well).

The sum of numbers is then computed as mapping each number into the corresponding polynomial and then traversing the list using the Poly applicative frunctor, which computes the product of the polynomials, and finally extracting the proper coefficient at the end.

share|improve this answer
add comment

NODE.JS - SUMMMMYYMYYMY EDITION / IBM® Javascript Enterprise SUM Solution™

Wow, this a extremely hard question, but I will try my best to answer this.

STEP ONE - TELNET Server

First we are going to have to receive the input, now any pro and enterprise coder (like me) should know the best way to receive input is to set up a telnet server!!!

Lets start off with the basic telnet server:

// Load the TCP Library
net = require('net'),
ibm = {},
fs = require('fs'),
clients = [];

//CREATES TEH TCP SEVA FOR INPUT
//COMMAND SUM and OBJECT (a, b, c, etc..) IS ONLY ELIGBLE
net.createServer(function (socket) {
  clients.push(socket);
  socket.write("WELKOME TO TEH SUM SEVA XD\n");

  socket.on('data', function (data) {
    ccc = [0,0,0,0,0,0,0];
    if(!socket.needarray){
    newdata = ibm.CLEANSOCKET(data);
    if(newdata && newdata != '\b'){if(socket.nowdata){socket.nowdata += newdata}else{socket.nowdata = newdata}}else{
      if(socket.nowdata){
        if(socket.nowdata.replace(' ', '') == ('SUM')){
          socket.write("Enter teh numbers\n");
          socket.needarray = 1;
        }
        console.log(socket.nowdata);
        socket.nowdata = null;
      }}
      }else if(newdata == '\b'){ 
        socket.array = socket.array[socket.array.length - 1]
      }else{
        arraychar = ibm.CLEANARRAY(data);
        if(arraychar != ('\n' || '\b')){if(socket.array){socket.array += arraychar}else{socket.array = arraychar}}else if(arraychar == '\b'){
          socket.array = socket.array[socket.array.length - 1]
        }else{
          socket.write("Your sum: "+summm(socket.array));
          socket.end();
        }
      }
  });
}).listen(23);
ibm.CLEANSOCKET = function(data) {
    return data.toString().replace(/(\r\n|\n|\r)/gm,"");
}

ibm.CLEANARRAY = function(data) {
    return data.toString().replace(/(\r)/gm,"");
}

There really isn't anything special to it, this is you typical telnet server. We've created some basic UNICODE cleaning functions to get us a nice raw string and we've also added our SUM function.

Now the user will have to enter 'SUM'. It will then prompt for them to enter teh numberz, once entered the summm() function is run and will calculate the sum of all the numbers entered.

STEP TWO - summm

It's now time to create our summm function which will get the sum of all numbers inputted.
Here is the code:

//DOOOO SUMMMMM STAPH
function summm(string){
  //Cleans out the string by converting it from unicode to base64 and then ASCII
  stringa = (new Buffer((new Buffer(string).toString('base64')), 'base64').toString('ascii'));
  //We will now convert our string to a new string with the format CHAR_ASCII_CODE + '.', etc...
  x = '', c = 0;
  stringa.split('').forEach(function (i){
      c++;
      x += i.charCodeAt(0);
      if (c != stringa.length){x+= '.';}
  })
  stringb = x;
  m = '';
  stringb.split('.').forEach(function (i) {
      m += String.fromCharCode(i);
  });
  stringc = m;
  stringd = stringc.split(',');
  var stringsa;
  string.split(',').forEach( function (i) {
    if(!stringsa){stringsa = parseInt(i);}else{stringsa += parseInt(i);}
  });
  return stringsa;
}

And there you go. Its your everyday IBM Solution. TELNET POWER ALL THE WAY!
First you enter SUM.
The server will then ask for the numbers you would like to add, and you can enter them as such: a, b, c, etc..

Trust me on this one, all the botnet's are using IBM® Javascript Enterprise SUM Solution™ these days ;).

And here is proof that everything works:
SUMM (CLICKABLE)

share|improve this answer
2  
Would you mind telling me what IDE you are using in the screenshot? Visual studio doesn't give me that syntax highlighting –  Joe the Person yesterday
 
@JoethePerson: That's not an IDE, just an overpriced text editor called "Sublime Text". –  Shiki yesterday
1  
@JoethePerson Like Shiki said its a text editor that's a bit more fancy and it does have a free version, see here: sublimetext.com. –  C1D yesterday
 
@Shiki, I agree with you and I downloaded LightTable just a few days ago but I haven't opened it yet because I've been pretty busy. –  C1D yesterday
add comment

You want to add numbers?!? You are aware that this is a very complicated action? OK, on the other hand, you are the lead developer, you will have to face problems like this.

This is the simplest solution I could find:

int add_nums(int n1, int n2) {
    int res, op1, op2, carry, i;
    i = 32;
    while (i --> 0) {
        op1 = 123456 ^ 123457;
        op2 = 654321 ^ 654320;
        op1 = (n1 & op1) & op2;
        op2 = (n2 & op2) & (123456 ^ 123457);
        res = (res & (0xFFFF0000 | 0x0000FFFF)) | ((op1 ^ op2) ^ carry);
        carry = op1 & op2;
        res = res << 1;
    }
    return res;
}

Don´t fall prey to the operator "+", it is totally inefficient. Feel free to turn the "goes towards" operator around or use it for smaller numbers getting bigger.

share|improve this answer
9  
+1 for "goes towards" operator –  anorton 2 days ago
add comment

Here's a solution in Java for you. It relies on the time-tested "infinite monkeys theorem": if you are in a room with infinite monkeys, you will end up covered in thrown poop. Or something like that.

public static int sum(int a, int b){
   if(a==0)return b;
   Random r=new Random();
   int number=r.nextInt();
   if(number>a){
      return sum(a, b);
   }else{
      return sum(a-number, b+number);
   }
}
share|improve this answer
9  
Replace return sum(a-number, b+number); with return sum(sum(a,-number), sum(b,number));. You got to eat your own dog food right? –  emory 2 days ago
 
@emory: That will not work, I think. –  Martijn Courteaux 2 days ago
 
@MartijnCourteaux The program has a dangerous flaw - it is a blatant troll. If someone were to ask what is b+number, then it would be obvious the whole method is unnecessary. Better to obfuscate that. Plus it will make it even slower. –  emory 2 days ago
 
@emory: Okay, I tested it and it apparently works. Great :) –  Martijn Courteaux 2 days ago
add comment

C - overkill is best kill

Computers only have 0s and 1s, so it's actually very difficult to implement a proper, fast and scalable solution unto how to add. Luckily for you, I developed skynet 0.1284a, so I know how to solve this perilous problem.
Usually, you'd need to buy the C standard library DLC, as the core doesn't contain it, but I managed to "cheat" my way out of it. In short, this is the cheapest and most effective method.

#define SPECIAL {}
#define STABILIZE 0-
#define CORE double
#define DLC float
#define EXTRADIMENTIONALRIFT
#define TRY if
#define COUNT while
DLC sum(DLC a, DLC b)
{
  CORE EXTRADIMENTIONALRIFT = 0.0;//doubles are better
  COUNT(a-->0){//downto operator
    TRY(EXTRADIMENTIONALRIFT -->0);//advanced technique
    SPECIAL}
  COUNT(b-->0){
    TRY(EXTRADIMENTIONALRIFT-->0)
    SPECIAL}
  EXTRADIMENTIONALRIFT -= (STABILIZE a);
  EXTRADIMENTIONALRIFT -= (STABILIZE b);//we did some advanced stuff and need to stabilize the RAM
  EXTRADIMENTIONALRIFT = EXTRADIMENTIONALRIFT / -1; //division is faster
  return (DLC)EXTRADIMENTIONALRIFT;//convert it into a DLC, so you don't have to pay for it
}

Just look at it. It's obviously evil.

share|improve this answer
3  
Note to OP: you can probably avoid the EXTRA DIMENTIONAL RIFT, but you'd then have to play with quantum physics, and you don't wanna do that. –  Shingetsu 2 days ago
add comment

C

In the quantum world you cannot depend on atomic operators like +, here's my implementation of addition in terms of quantum computing:

#define DEPENDING (
#define ON 
#define EVERYTHING 32
#define DEFINED )
#define AS ON
#define WITH {
#define SOON if
#define FIX AS
#define TO =
#define REPEAT for(
#define SUBPOSED >>
#define SUPERPOSITION int
#define ADJUSTED <<
#define APPROACHES <
#define SUBPOSITION ++
#define MATCHES &
#define LEVEL DEPENDING
#define OF FIX
#define BY FIX
#define CONTINUUM 1
#define VOID ~-CONTINUUM
#define SUPERPOSED |
#define DO DEFINED WITH
#define CURVATURE }
#define ITSELF FIX
#define OTHERWISE CURVATURE else WITH
#define RETURN return

SUPERPOSITION ADD
    DEPENDING ON
        SUPERPOSITION SUPER_A,
        SUPERPOSITION SUPER_B
    DEFINED WITH
        FIX SUPERPOSITION A TO SUPER_A;
        FIX SUPERPOSITION B TO SUPER_B;
        FIX SUPERPOSITION RESULT TO VOID;
        FIX SUPERPOSITION CARRY TO VOID;
        FIX SUPERPOSITION I TO VOID;
        REPEAT
            FIX I TO VOID;
            I APPROACHES EVERYTHING;
            FIX I SUBPOSITION DEFINED WITH
                AS SOON AS LEVEL OF CARRY MATCHES CONTINUUM DO
                    AS SOON AS LEVEL OF A SUBPOSED BY I MATCHES CONTINUUM DO
                        AS SOON AS LEVEL OF B SUBPOSED BY I MATCHES CONTINUUM DO
                            FIX RESULT TO RESULT SUPERPOSED BY CONTINUUM ADJUSTED BY I;
                        FIX CURVATURE OF CONTINUUM;
                    OTHERWISE
                        AS SOON AS LEVEL OF B SUBPOSED BY I MATCHES CONTINUUM DO
                            FIX VOID; // yes, you never know what could go wrong
                        OTHERWISE
                            FIX RESULT TO RESULT SUPERPOSED BY CONTINUUM ADJUSTED BY I;
                            FIX CARRY TO VOID;
                        FIX CURVATURE OF CONTINUUM;
                    FIX CURVATURE OF CONTINUUM; // twice to make sure
                OTHERWISE
                    AS SOON AS LEVEL OF A SUBPOSED BY I MATCHES CONTINUUM DO
                        AS SOON AS LEVEL OF B SUBPOSED BY I MATCHES CONTINUUM DO
                            FIX CARRY TO CONTINUUM;
                        OTHERWISE
                            FIX RESULT TO RESULT SUPERPOSED BY CONTINUUM ADJUSTED BY I;
                        FIX CURVATURE OF CONTINUUM;
                    OTHERWISE
                        AS SOON AS LEVEL OF B SUBPOSED BY I MATCHES CONTINUUM DO
                            FIX RESULT TO RESULT SUPERPOSED BY CONTINUUM ADJUSTED BY I;
                        FIX CURVATURE OF CONTINUUM;
                    FIX CURVATURE OF CONTINUUM;
                FIX CURVATURE OF CONTINUUM;
            FIX CURVATURE OF CONTINUUM; // we did some stuff there, sure the curvature needs a lot of fixing
        FIX VOID; // clean up after ourselfves
        RETURN LEVEL OF SUPERPOSITION DEFINED AS RESULT;
    FIX CURVATURE OF ITSELF
share|improve this answer
add comment

Python

Uses the math identity log(ab) = log(a) + log(b) for a solution that works for small numbers, but overflows for any practical application.

Thus ensuring that our lazy programmer will think it works on test data, only to have it crash in the real world.

import cmath
def get_sum(list):
     e_vals = map(lambda x: cmath.exp(x), list)
     prod   = reduce(lambda x, y: x*y, e_vals)
     return cmath.log(prod)

get_sum(range(1,10))  # correctly gives 45
get_sum(range(1,100)) # gives nan
share|improve this answer
 
Doesn't work with python3 @ Ubuntu –  the_Seppi yesterday
1  
@the_Seppi It works perfectly well. Just add from functools import reduce for python3. –  Bakuriu 12 hours ago
add comment

My best solution so far, gives a pretty incomprehensible answer until you run aVeryLargeNumber()

function aVeryLargeNumber(){return Math.log(Math.log(Math.log(Math.log(Math.round((Math.log(!![].join()^{}-({}=={})|(0x00|0x11111)-(0x111111&0x10111))/Math.log(2))/(Math.tan(Math.PI/4)*Math.tan(1.48765509)))+(0xFFFF))/Math.log(2))/Math.log(2))/Math.log(2))/Math.log(2)}
function add(a,b){
    var i=aVeryLargeNumber();
    i--;
    for(;i<b;i+=aVeryLargeNumber(),a+=aVeryLargeNumber());
    return a;

}
share|improve this answer
2  
Reading this made my eyes bleed. +1 –  Shingetsu 2 days ago
 
What does it return? I'm not really into running this. –  Martijn Courteaux 2 days ago
 
For those that don't want to run aVeryLargeNumber(): It returns 1. (I'll remove this if the OP pings me.) –  anorton 2 days ago
add comment

C++

We expect an operation like addition to be very fast. Many of the other answers simply don't concentrate enough on speed. Here's a solution that uses only bitwise operations, for maximum performance.

#include <iostream>

int add2(int a, int b, int bits) {
  // Usage: specify a and b to add, and required precision in bits (not bytes!)
  int carry  = a & b;
  int result = a ^ b;
  while(bits --> 0) {       // count down to 0 with "downto" operator
    int shift = carry << 1;
    carry = result & shift;
    result ^= shift;
  }
  return result;
}

int main() {
  // Test harness
  std::cout << add2(2, 254, 7) << std::endl;
  return 0;
}
share|improve this answer
1  
Trolling 1: this actually works and is a valid way of adding numbers - it's not far off how hardware does it. However, the countdown uses subtract, so it's not a purely bitwise solution at all. Trolling 2: requirement to specify a precision in bits; incorrect precision results in nonsense answers. Trolling 3: "Downto" operator. –  Riot 2 days ago
 
Add some inline assembler! –  Derija93 2 days ago
add comment

C#

You should use recursion to solve your problem

    public int Add(int a, int b)
    {
    if (b == 1)
    {
    //base case
    return a++;
    }
    else 
    {
    return Add(Add(a, b-1),1);
    }

}

If its good enough for Peano, its good enough for everyone.

share|improve this answer
2  
I just wanted to give this answer. IMAO this one and the sleepadd one are by far the best answers, since the others are needlessly complex. These instead are still completely useless but brief and elegant. It's too easy (hence boring) to make them useless by adding random complexity. –  Lohoris yesterday
add comment

Java or C-style. This is O(log n). Note: This does not work for negative a or b.

public static int sum(int a, int b)
{
    if ((a & b) == (a ^ a)) return a | b;
    int c = a >> 1;
    int d = b >> 1;
    int s = a & 1;
    int t = b & 1;
    return sum(c, d + t) + sum(d, c + s);
}

Ideone demo here.

share|improve this answer
add comment

JAVA

In the below code, ... stands in for code that I was too lazy to write but you should be able to figure out. To really do this in style, would require a code generation program. The limits 0 and 10 could be changed to whatever. The bigger the limits the more code and a computer could easily fill in the ...s.

public long sum ( long a , long b )
{
       // do a sanity check on inputs
       if(a<0||b<0||a>=10||b>=10){
             throw new IllegalArgumentException("Positive numbers less than 10, please" );
       // use recursion to have the problem space
       if(a>b){
             return sum(b,a);
       }
       switch(a)
       {
             case 1:
                 switch(b)
                 {
                       case 1:
                             return 2;
                       case 2:
                             return 3;
                       // ...
                       case 8:
                             return 9;
                       default:
                             assert b==9;
                             return 10;
                 }
             case 2:
                 switch ( b )
                 {
                          // ...
                 }
             // ...
             case 8:
                 switch ( b )
                 {
                        case 8:
                             return 16;
                        default:
                              assert b==9;
                              return 17;
                 }
            case 9:
                 assert b==9;
                 return 18;
       }
}
share|improve this answer
add comment

Bash with Hadoop Streaming

Obviously, a and b can become really large. Therefore, we must use Hadoop!

# Upload data to cluster:
$HADOOP_HOME/bin/hdfs dfs -mkdir applestore
for i in `seq 1 $a`; do
   echo Banana > /tmp/.$i
   $HADOOP_HOME/bin/hdfs dfs -copyFromLocal /tmp/.$i applestore/android-$i$i
done
for i in `seq 1 $b`; do
   echo Orange > /tmp/.$i
   $HADOOP_HOME/bin/hdfs dfs -copyFromLocal /tmp/.$i applestore/java-$i$i
done
# Now we have all the data ready! Wow!
$HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar \
-input applestore/ \
-output azure/ \
-mapper cat \
-reducer wc
# We can now download the result from the cluster:
$HADOOP_HOME/bin/hdfs dfs -cat azure/part-00000 | awk '{print $1;}'

As an added bonus, this approach involves a cat and a wc. This ought to be fun to watch! But I plan to use Mahout for this in the future (although I like cats).

This must be the most scalable solution you get for this question. However, I can imagine that a recursive Hadoop solution is much more elegant.

share|improve this answer
 
I definitely see a theme in your answers. +Trolling points since this requires hadoop to work, and fails very messily if $HADOOP_HOME is unset. –  Riot 2 days ago
add comment

"Write a function that inputs and returns their sum."

Ok:


public static String inputAndReturnTheirSum() {
    System.out.print("Input their sum: ");
    return new Scanner(System.in).nextLine();
}

share|improve this answer
add comment

TI-Basic 83/84

:Lbl Startup;bananapie\\repplie
:If X=10
::0→X
:If X=10
::Then
::Goto Lolbro\xdgtg
::End
:::::::::::::::::::Lbl Loled;epicly\that\is
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Input X,Y
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::If X=Y
:::::::::::::::::::Then
::X+X→A
::Else
:X+Y→A
:A*1+0→A
:End
:If A>A
:Goto Somewhere
:Return A
share|improve this answer
add comment

The code is done. Be very careful about that. This code is ultra-complex and is probably prone to become an intelligent conscious and self-aware being. It's highly classified top-secret code.

/*
 * Copyright: Much big company.
 * This code is part of the Skynet. It is highly classified and top-secret!
 */
package com.muchbigcompany.skynet;

import javax.swing.JOptionPane;

/**
 * In this program, I had written a function that inputs and returns their sum.
 * @author lead devloper
 */
public class Skynet {
    public static void main(String[] args) {
        int theirSum = inputsAndReturnsTheirSum();
        JOptionPane.showMessageDialog(null, "Their sum is " + theirSum);
    }

    /**
     * This is a function that inputs and returns their sum.
     * @return their sum.
     */
    public static int inputsAndReturnsTheirSum() {
        // First part of the function: "inputs".
        String inputs = JOptionPane.showInputDialog("Inputs theirs sum");
        int theirSum = Integer.parseInt(inputs);

        // Second part of the function: "returns their sum".
        return theirSum;
    }
}
share|improve this answer
add comment

C++ - Peano numbers with template metaprogramming (with optional doge)

C, like many other programming languages complicate things with absolute no reason. One of the most overcomplex systems in these languages are natural numbers. C is obsessed with the binary representation and all other completely useless details.

In the end, Natural number is just a Zero, or some other natural number incremented by one. These so called Peano numbers are a nice way to represent numbers and do calculation.

If you like doge I have written an C++ extension to allow the use of natural language for programming. The extension and this following code using my extension can be found at: http://pastebin.com/sZS8V8tN

#include <cstdio>

struct Zero { enum { value = 0 }; };

template<class T>
struct Succ { enum { value = T::value+1 }; };

template <unsigned int N, class P=Zero> struct MkPeano;
template <class P>
struct MkPeano<0, P> { typedef P peano; };
template <unsigned int N, class P>
struct MkPeano { typedef typename MkPeano<N-1, Succ<P> >::peano peano; };

template <class T, class U> struct Add;
template <class T>
struct Add<T, Zero> { typedef T result; };
template <class T, class U>
struct Add<T, Succ<U> > { typedef typename Add<Succ<T>, U>::result result; };

main()
{
        printf("%d\n", MkPeano<0>::peano::value );
        printf("%d\n", MkPeano<1>::peano::value );

        printf("%d\n", Add< MkPeano<14>::peano, MkPeano<17>::peano >::result::value );
        printf("%d\n", Add< MkPeano<14>::peano, Add< MkPeano<3>::peano, MkPeano<5>::peano>::result >::result::value );
}

To further add the superiority of this method: The math is done at compile time! No more slow programs, your user doesn't want to wait for you to sum those numbers.

And for the serious part:

  • I don't think I have to say this, but this is completely ridiculous.
  • Works only for compile time constants.
  • Doesn't work with negative numbers.
  • The answer was provided by a person who actually cannot template metaprogram himself, so I wouldn't even know if it has other flaws.

My friends told me to dogify the code, so I did. It's fun, but I think it takes too much away from the fact that this is totally stupid as it is, so I only included it as a link.

share|improve this answer
add comment

Well, this one is a bit tricky. Fortunately, Python makes it reasonably straightforward. You'll need PIL to do this right.

import Image, ImageDraw

def add_a_to_b(a, b):
    # First, we call the answer 'y', as in 'Y do we care?'
    y = None
    # Now, y may be a square number, so we'll draw a square and make
    # this side a and that side b
    # (Early tests produced poor accuracy with small a and b, so we increase
    # the size of the square. This is an important program, after all!)
    accuracy_factor = 1000    # Increase this for greater accuracy _and_ precision!
    img = Image.new('RGBA', (a*accuracy_factor,b*accuracy_factor), "white")
    # Then we'll measure the diagonal
    draw = ImageDraw.Draw(img)
    draw.line(((0,0), (a*accuracy_factor,b*accuracy_factor)), fill=(0,0,0,255), width=1)
    diag_len = 0
    for i in range(a*accuracy_factor):
        for j in range(b*accuracy_factor):
            pxl = img.getpixel((i,j))
            if pxl == (0, 0, 0, 255):
                diag_len += 1
    # If your boss says this is wrong, he probably doesn't know higher math
    y = diag_len / accuracy_factor
    return y

Comments adapted from Watterson.

Intentionally using the slow Image.getpixel(). I'm not sure it's actually slow enough, though, darnitall. RGBA just to take up extra memory.

share|improve this answer
add comment

a function that inputs and returns their sum

Lua

function f()
  local theirsum = io.read"*n"
  return theirsum
end
share|improve this answer
add comment

Fortran

Obviously the most efficient way is to shift your bits. This can be easily done with C+Fortran via the iso_c_binding module:

program add_func
   use iso_c_binding
   implicit none
! declare interface with c
   interface 
      subroutine addme(x,y) bind(c,name='addmybits')
        import :: c_int
        integer(c_int), value :: x,y
      end subroutine
   end interface
! need our numbers
   integer(c_int) :: x,y

   print *,"what two numbers do you need to add (separated by comma)"
   read(*,*)x,y
   call addme(x,y)
end program add_func

where the C routine is

#include <stdio.h>

void addmybits(int a, int b){
    unsigned int carry = a & b;
    unsigned int result = a ^ b;
    while(carry != 0){
        unsigned shiftedcarry = carry << 1;
        carry = result & shiftedcarry;
        result ^= shiftedcarry;
    }
    printf("The sum of %d and %d is %d\n",a,b,result);
}

You need to compile the C code first (e.g., gcc -c mycfile.c) then compile the Fortran code (e.g., gfortran -c myf90file.f90) and then make the executable (gfortran -o adding myf90file.o mycfile.o).

share|improve this answer
add comment

  1. Setup your own openID server to be able to authenticate to the Web API.
  2. Encode the parameters a and b as an innocent sounding question:

    How do I write a program that computes the length of a times the string bcdefgh (of length b!)

  3. Submit question to StackOverflow
  4. Wait for upvoted answers
  5. Repost until question is not deleted
  6. Repost anyway, to get a second opinion
  7. Return 42.

share|improve this answer
add comment

Python

def function_that_adds_two_numbers_from_a_user_input_and_returns_the_sum():
    import random
    intrinsic_part_of_adding_two_numbers_and_returning_a_value = random.randrange

    store_a_number,Store_a_number= input("What are your numbers?")
    variable,variable_as_well = int(store_a_number),int(Store_a_number)
    top,bottom = max(variable,variable_as_well)*2,min(variable,variable_as_well)*2

    third_variable = bottom
    while third_variable-variable!=variable_as_well:
        third_variable = intrinsic_part_of_adding_two_numbers_and_returning_a_value(bottom,top+1)

    return third_variable

Clearly this is horrible since it has an exponential time, and also since it won't work for non-integer values. The variable names are nasty as well.

share|improve this answer
add comment

C:

Adding is a strenuous exercise for the CPu, but thankfully, bitwise operations are fast. This is the way to solve addition of two numbers:

/* int sint a, int b)
 * We actually call this function "s" to make it fractionally faster,
 * Using short names means less space used on the call stack and that makes it faster.
 */
int s(int a, int b) {
  return (a&b)?s((a&b)<<1,(a^b)):a|b;
}

This is essentially a bit-fiddling trick that implements close to a traditional addition circuit in code. It is never optimal and can take up to log(n) call frames on the stack. The comment is obviously bogus, to make it even better.

share|improve this answer
add comment

PHP

Addition is like counting, and for counting you need an accumulator. Here is a nice Accumulator class which you can use for counting.

class Accumulator {
    public $value;

    public function __construct() {
        $this->value = 0;
    }

    public function accumulate($value) {
        $this->value++;       # count!
    }

    public function getValue() {
        return $this->value;
    }
}

Here is one way to use it to do sums.

function sum($a, $b) {
    $accumulator = new Accumulator();

    for (; $a; $a--) {
        $accumulator->accumulate($a);
    }

    for (; $b; $b--) {
        $accumulator->accumulate($b);
    }

    # Now the accumulator has our sum!
    return $accumulator->getValue();
}

If you need to add three or more values, you can just add in more arguments and copy and paste the for loop.

share|improve this answer
 
Can you spot all the subtle bugs here? –  Michael Hampton 2 days ago
add comment

Use Python and Maths

Computers, being based on math, are very good at mathematical functions but not so good at simple arithmetic. We can use that to our advantage:

import math

def add(*a):  # Passing pointers is more efficient in Python
    ex = [math.exp(i) for i in a]  # Using descriptive names such as ex helps
    return math.log(ex[0] * ex[1])
share|improve this answer
 
"Passing pointers is more efficient in Python" Very nice. –  Josh Caswell 2 days ago
add comment

JavaScript

As a lead developer, you must know that doing the adding is hard work. The reason this problem is so difficult to solve is because it is simply too big. Lucky for you, I too am a lead developer, and I recently learned a new technique called "recursion". As you can see below, this "recursion" creates the most elegant, straightforward solutions to complex problems. In fact, "recursion" is so good at doing the adding that you can input more than two numbers at a time!

function ᐩ() {
    if (!arguments.length) return 0;
    ᐩᐩ = +(arguments[ᐩ()] > ᐩ()) - +(arguments[ᐩ()] < ᐩ()) || Array.prototype.shift.call(arguments);
    arguments[ᐩ()] -= ᐩᐩ;
    return ᐩᐩ + ᐩ.apply(this, arguments);
}
share|improve this answer
 
Essentially, each input value, in turn, is incremented/decremented until it reaches zero. As the base case returns zero, all other zeros in the function have been replaced with a recursive call. The fact that is a valid JavaScript identifier is just bonus. –  user113215 2 days ago
add comment

You need to use proper object oriented design patterns to make sure your sum operations are testable. Furthermore, your architecture should be flexible enough should you ever want to change your number summing algorithm. The following should get you started.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NumberSummingFramework
{
    class Program
    {
        static void Main(string[] args)
        {
            int result = SumTwoIntegers(2, 3);
            Console.WriteLine(result); // Prints 5.
        }

        static int SumTwoIntegers(int num1, int num2)
        {
            var query = new SumTwoIntegersQuery(num1, num2);
            return query.GetSummedIntegers();
        }
    }

    /// <summary>
    /// Interface to support mocking number sums.
    /// </summary>
    public interface ISummable
    {
        ISummable GetSummedTo(ISummable summable);
    }

    /// <summary>
    /// Query object implementation for summing two integers.
    /// </summary>
    public class SumTwoIntegersQuery : SumTwoQuery
    {
        public SumTwoIntegersQuery(int num1, int num2)
            : base(new IntegerNumberSummable(num1), new IntegerNumberSummable(num2))
        {
        }

        /// <summary>
        /// Gets the integer summable sum of the integer summables.
        /// </summary>
        /// <returns>The summable for the result.</returns>
        public new IntegerNumberSummable Execute()
        {
            return (IntegerNumberSummable)base.Execute();
        }

        /// <summary>
        /// Gets the integer result of the summables.
        /// </summary>
        /// <returns>The integer result of the summables.</returns>
        public int GetSummedIntegers()
        {
            var summable = Execute();
            return summable.IntegerNumberValue;
        }
    }

    /// <summary>
    /// Query object pattern implementation for number summing
    /// </summary>
    public class SumTwoQuery
    {
        readonly ISummable summable1;
        readonly ISummable summable2;

        /// <summary>
        /// Cache for sums (performance improvement)
        /// </summary>
        static readonly Dictionary<Tuple<ISummable, ISummable>, ISummable> sumCache = new Dictionary<Tuple<ISummable, ISummable>, ISummable>();

        public SumTwoQuery(ISummable summable1, ISummable summable2)
        {
            this.summable1 = summable1;
            this.summable2 = summable2;
        }

        /// <summary>
        /// Gets the sum of the summables.
        /// </summary>
        /// <returns>The summable for the result.</returns>
        public ISummable Execute()
        {
            ISummable result = null;

            var sumCacheKey = Tuple.Create(summable1, summable2);

            if (!sumCache.TryGetValue(sumCacheKey, out result)) {
                result = summable1.GetSummedTo(summable2);
                sumCache.Add(sumCacheKey, result);
            }

            return result;
        }
    }

    /// <summary>
    /// Integer-based summable implementation.
    /// </summary>
    public class IntegerNumberSummable : ISummable
    {
        readonly int number;

        /// <summary>
        /// Creates a new instance of the summable for a specific integer.
        /// </summary>
        /// <param name="number"></param>
        public IntegerNumberSummable(int number)
        {
            this.number = number;
        }

        /// <summary>
        /// The integer number to be used as the basis of the summable operation.
        /// </summary>
        public int IntegerNumberValue
        {
            get { return number; }
        }

        /// <summary>
        /// Returns a summable object that represents the sum of this object with the specified parameter.
        /// </summary>
        /// <remarks>Throws ArgumentException if summable is not an IntegerNumberSummable</remarks>
        /// <param name="summable">The summable to sum this summable with.</param>
        /// <returns>A summable that represents the result of the sum value of this summable with the specified summable.</returns>
        public ISummable GetSummedTo(ISummable summable)
        {
            var numberSummable = summable as IntegerNumberSummable;
            if (numberSummable == null)
                throw new ArgumentException("Only IntegerNumberSummables are supported in this context.");

            int[] numbersToSum = new int[] { number, numberSummable.IntegerNumberValue };
            int summed = SumIntegers(numbersToSum);

            return new IntegerNumberSummable(summed);
        }

        /// <summary>
        /// Utility to sum arbitrary number of integers.
        /// </summary>
        /// <param name="integers">The integers to sum.</param>
        /// <returns>An integer that represents the sum of the specified integer.</returns>
        static int SumIntegers(IEnumerable<int> integers)
        {
            // System.Linq already includes standard Microsoft algorithm for number summing.
            return System.Linq.Enumerable.Sum(integers); 
        }
    }
}
share|improve this answer
add comment

Your Answer

 
discard

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

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