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

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

locked by Doorknob 冰 May 11 at 22:35

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

closed as too broad by TheDoctor, WallyWest, Quincunx, user80551, squeamish ossifrage May 7 at 12:42

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.

31  
You can use my lightweight jQuery plugin: $.sum=function(a,b){return a+b};. –  Blender Dec 28 '13 at 13:51
5  
I knew I'd get a jQuery reference sometime –  scrblnrd3 Dec 28 '13 at 13:51
5  
Brilliant English :p –  Martijn Courteaux Dec 28 '13 at 17:39
5  
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 Dec 28 '13 at 18:42
5  
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 Dec 28 '13 at 20:57

75 Answers 75

up vote 70 down vote accepted

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
11  
i -= -1. Very creative. I already reached the vote limit today, but I will upvote your answer as soon as I can. –  Victor Dec 28 '13 at 16:20
    
As long as you insist that anything other than 6755 & 1436 is undefined behavior, despite OP's perception that most numbers seem to work... –  Trojan Dec 29 '13 at 2:03
    
What is the meaning of '=>'? –  Ilya_Gazman Dec 29 '13 at 14:01
2  
@Babibu I have never written a line of C# in my life but this is almost certainly a lambda expression. –  thwd Dec 29 '13 at 14:39
3  
uh oh, var x = Sum(0, 4) DivideByZeroException. –  psgivens Jan 6 at 18:42

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
5  
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 Dec 28 '13 at 16:26
4  
@Shingetsu: what, you're saying nobody else has heard of mp3 codecs? :P –  Riot Dec 28 '13 at 18:00
7  
I'm saying very few people actually make the association. Lame IS lame though. Vorbis master race. –  Shingetsu Dec 28 '13 at 18:02
7  
+1 for massively off-topic audio encoder wars diatribe :) –  Riot Dec 28 '13 at 18:03
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 Dec 28 '13 at 19:44

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
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 Dec 28 '13 at 22:51
3  
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 Dec 29 '13 at 18:41

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
2  
+1 although it feels too readable for code trolling... –  Marc Claesen Jan 2 at 22:09

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

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
16  
+1 for "goes towards" operator –  anorton Dec 28 '13 at 17:28

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
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 Dec 29 '13 at 16:48
1  
@JoethePerson: That's not an IDE, just an overpriced text editor called "Sublime Text". –  Shiki Dec 29 '13 at 16:55
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 Dec 29 '13 at 17:31
    
@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 Dec 29 '13 at 17:31
1  
+1 for Sublime :P –  thefourtheye Jan 3 at 9:32

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
12  
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 Dec 28 '13 at 16:13
    
@emory: That will not work, I think. –  Martijn Courteaux Dec 28 '13 at 17:18
    
@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 Dec 28 '13 at 17:20
    
@emory: Okay, I tested it and it apparently works. Great :) –  Martijn Courteaux Dec 28 '13 at 17:37

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
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 Dec 28 '13 at 17:34

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
    
Doesn't work with python3 @ Ubuntu –  the_Seppi Dec 29 '13 at 15:07
1  
@the_Seppi It works perfectly well. Just add from functools import reduce for python3. –  Bakuriu Dec 30 '13 at 20:07

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
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 Dec 29 '13 at 13:23
1  
The reasoning is flawless! –  recursion.ninja Jan 2 at 19:30
    
Shouldn't it be ++a instead of a++? (Edits must be at least 6 characters; is there something else to improve in this post?) stupid stupid stupid stupid SO –  Lohoris Jan 4 at 11:53
    
@Lohoris - Yes, Yes it should. Fixed –  Haedrian Jan 4 at 13:08

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
3  
Reading this made my eyes bleed. +1 –  Shingetsu Dec 28 '13 at 17:05
    
What does it return? I'm not really into running this. –  Martijn Courteaux Dec 28 '13 at 17:17
    
For those that don't want to run aVeryLargeNumber(): It returns 1. (I'll remove this if the OP pings me.) –  anorton Dec 28 '13 at 19:14

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
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 Dec 28 '13 at 16:57
    
Add some inline assembler! –  Derija93 Dec 28 '13 at 23:39

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
1  
Wow. Such doge. Very upvote. –  Marc Claesen Jan 2 at 22:12

I stopped trusting computers when I learned about floating point errors.

This JavaScript relies on precise human error checking:

while(prompt("Is this the answer: " + Math.round(Math.random()* 1000000)) !== "yes") {}
share

"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
    
This is my favourite. :D –  Jeroen Bollen May 6 at 19:32

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

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
1  
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 Dec 29 '13 at 3:12

Ignore all those silly people with their non-generic and untestable manners. We need a performant, extensible and simple library for a project of such scale. It must support extension and substituton at every point of the code. For that, we need an equally extensible and simple language, that's why the best candidate is C#.

This is why I present you the beta version of my Operable Commons Library Enterprise Edition, version 0.8.4.4_beta1.3a_rev129857_dist29.12.13/master, which at this version exposes a IOperable interface, a IAddable interface so you can use your own efficient adding methods, and a default implementation of IAddable: the Addable class, which uses extremely efficient bitwise addition, without cheating and using the slow native subtraction for carry shifting. Of course, like any good library, it comes with a factory for every type it supports. The library also follows the principles of "handle it yourself", so you must guarantee that the input is valid and that the desired output is feasible, since it will not check for invalid data. Here it is (This code is licensed under the Microsoft Corporation Read-Only Proprietary Dont-Touch-This Obstructive License, Revision 3.1):

public interface IOperable {
    uint Value {get; set;}
}

public interface IAddable : IOperable {
    IAddable Add(IAddable a, IAddable b);
}

public class Addable : IAddable {
    public uint Value {get; set;}

    public Addable(uint value) {
        Value = value;
    }

    public IAddable Add(IAddable a, IAddable b) {
        uint carry = a.Value & b.Value;
        uint result = a.Value ^ b.Value;
        while (carry != 0) {
            uint shiftedcarry = carry << 1;
            carry = result & shiftedcarry;
            result ^= shiftedcarry;
        }
        return new Addable(result);
    }
}

public static class OperableFactory {
    public static IAddable GetAddable(uint value) {
        return new Addable(value);
    }
}
share

JavaScript

Programming is all about algorithm. Let's go back to basic algorithm what we learn at the age of 3 - fingers counting.

var fingers = 0;
var hands = 0;
var FINGER_NUMBER = 5;

/* MEAT */
function sum(a,b){
    while(a-- > 0) {
        finger_inc();
    }
    while(b-- > 0) {
        finger_inc();
    }

    return count_hands_and_fingers(); // We count the number of hands and fingers
}

/* Private functions */
function finger_inc(){
    if(++fingers >= FINGER_NUMBER) {
        hands++;
        fingers = 0;
    }
}

function count_hands_and_fingers() {
    var total_count = 0;
    total_count = hands * FINGER_NUMBER;
    total_count += fingers;
    return total_count;
}

document.write(sum(1,50));
  • Firstly, being a lead developer, let's have a wise language choice - cross-platform, light-weight and portable.

  • Secondly, have a global vision. Use Global var.

  • Thirdly, ++s and --s

  • Same as YFS (You-Finger-System), this does not support negative numbers

  • Finally, you can alter FINGER_NUMBER according to the number of fingers you have.

JSFiddle: http://jsfiddle.net/e3nc5/

share
    
But what if you need to count over 10? I don't have 3 hands! –  AJMansfield May 6 at 23:52
    
Hotfix:Use feet, you can do that up to 20. Cheers, david. –  David May 11 at 8:39

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

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

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

a function that inputs and returns their sum

Lua

function f()
  local theirsum = io.read"*n"
  return theirsum
end
share

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

C++

Of course you are gonna need some template magic:

template<int I> struct identity {
    static const int value = I;
};

template<int A, int B> struct sum {
    static const int value = identity<A>::value + identity<B>::value;
};

auto main(int argc, char* argv[]) -> int {
    std::cout << sum<1, 3>::value;
    return 42;
}
share

JAVA

Hard problem.

It is known that in computer science there are problems that verifying their answers is easier than finding them. So, you should use a random algorithm for guessing the solution, then verify it (efficiently!), and hope to get the right result in reasonable time:

public long sum(int a, int b)
{
    Random r=new Random();
    While(15252352==15252352)
    {
        long sum=r.nextLong(); // guess the solution
        if (sum - a == b)      // verify the solution
            return sum;
    }
}
share
    
Add language name –  Wasi Dec 30 '13 at 19:18

This function is under patent of my company, I can provide you an obfuscated licensed copy of it:

Javascript:

function sum(a,b) { return eval(atob('YSti')) };

Usage:

sum([arg1],[arg2]);
share

Python

Programming is about fault tolerant. The following is an implementation of sum that will add anything without fussing out. It will transparently sort the elements in the order that can be added. In case, its not addable, it will flag it as NaN.

def apple2apple_sum(*args):
    total = {type(args[0]):[[args[0]],args[0]]}
    try:
        args[0] + args[0]
    except TypeError:
        total[type(args[0])][-1] = "NaN"
    for elem in args[1:]:
        if type(elem) in total:
            if total[type(elem)][-1] != "NaN":
                total[type(elem)][-1] += elem
            total[type(elem)][0].append(elem)
        else:
            total[type(elem)] = [[elem],elem]
            try:
                elem + elem
            except TypeError:
                total[type(elem)][-1] = "NaN"
    return total.values()

>>> apple2apple_sum(1,2,3,'a', 'b', 4, 5.1, 6.2, 'c', map, 10, sum)
[[['a', 'b', 'c'], 'abc'], [[<built-in function map>, <built-in function sum>], 'NaN'], [[5.1, 6.2], 11.3], [[1, 2, 3, 4, 10], 20]]
share

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

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