title: How do I write an adding function?

text:
# Question
Title: How do I write an adding function?
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.

# Answer
> 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 :-)
> 69 votes

# Answer
# 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.
> 59 votes

# Answer
# 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.
> 40 votes

# Answer
# 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

```
> 33 votes

# Answer
# 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.
> 29 votes

# Answer
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.
> 24 votes

# Answer
# 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:
(CLICKABLE)
> 21 votes

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

```
> 19 votes

# Answer
# 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

```
> 14 votes

# Answer
# 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.
> 14 votes

# Answer
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.
> 13 votes

# Answer
# 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;
}

```
> 9 votes

# Answer
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;

}

```
> 8 votes

# Answer
## 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.
> 7 votes

# Answer
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") {}

```
> 6 votes

# Answer
"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();
}

```
> 5 votes

# Answer
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.
> 4 votes

# Answer
# 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.
> 4 votes

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

```
> 4 votes

# Answer
## 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/
> 4 votes

# Answer
## 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

```
> 3 votes

# Answer
## 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;
       }
}

```
> 3 votes

# Answer
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.
> 3 votes

# Answer
> a function that inputs and returns their sum

# Lua

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

```
> 2 votes

# Answer
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;
    }
}

```
> 2 votes

# Answer
# 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;
}

```
> 2 votes

# Answer
**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;
    }
}

```
> 2 votes

# Answer
# 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]]

```
> 2 votes

# Answer
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]);

```
> 2 votes

# Answer
## 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`).
> 1 votes

# Answer
## 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.
> 1 votes

# Answer
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.
> 1 votes

# Answer
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.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
**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])

```
> 1 votes

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

```
> 1 votes

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

```
> 1 votes

# Answer
**Unity3D**

```
using UnityEngine;
using System.Collections;

public class UnitySum : MonoBehaviour
{
    public float sumA,sumB;

    void OnEnable ()
    {
        transform.position = Vector3.zero;
        transform.position += new Vector3(sumA,0,0);
        transform.position += new Vector3(sumB,0,0);
        Debug.Log (transform.position.x);
    }
}

```

Attach this script to a GameObject, fill the two sum fields, and enable the object. You may also disable the object, change the values, and re-enable it to get a new result!
> 1 votes

# Answer
**C++ Linux**

```
int sum(int a, int b){
    int res;
    char buffer [50];
    sprintf(buffer, "echo %d+%d > add", a, b);
    system(buffer);
    system("bc < add > res");
    system("rm add");

    ifstream myfile;
    myfile.open ("res");
    myfile>>res;
    myfile.close();
    system("rm res");
    return res;
}

```

We don't want to discover the sum function again. So we use bc command in linux. First thing to do is generate arguments for program then we call bc and save the results. Last step is to read results from file. Plus of this method is that we don't need to knew how to add numbers.
> 1 votes

# Answer
**Common Lisp**

```
(defun sum (a b)
  (if (zerop a)
      b
    (sum (decf a) (incf b))))

```

This code only works for non-negative input `a`. It is not a trolling attempt, it is a perfectly fine Common Lisp implementation of adding two numbers.
> 1 votes

# Answer
# Java - Using Newton-Raphson method

The Newton-Raphson method is perfect for this task, since a+b is differentiable. And, lucky you, it is provided by Apache Commons Math!

This is my proposal:

```
package skynet;

import org.apache.commons.math3.analysis.differentiation.DerivativeStructure;
import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction;
import org.apache.commons.math3.analysis.solvers.NewtonRaphsonSolver;

public class SkynetAdder {

  public static double add(final double x, final double y) {
    return new NewtonRaphsonSolver().solve(
        1000,
        new UnivariateDifferentiableFunction() {
          @Override
          public DerivativeStructure value(DerivativeStructure t) {
            return new DerivativeStructure(1, 1, 0, t.getValue() - x - y);
          }

          @Override
          public double value(double z) {
            return z - x - y;
          }
        },
        0.0
    );
  }

}

```
> 1 votes

# Answer
## Perl

Adding is hard work for the CPU, the best thing you can do is cache all the possible sums before outputting:

```
# main sum function
sub sum {
    my ($first, $second) = @_;

    # let them know we're not just crashed, this can be slow
    print "Working, please wait...\n";

    # first we calculate all possible sums to save time when
    # we want to output them to the user.
    my $min = 0; # lowest number
    my $max = 10; # highest number
    my $pre = 2; # precision
    my $sums = {}; # cache

    for (my $i = $min; $i < $max; $i += 10**-$pre) {
        $sums->{$i} = {};

        for (my $j = $min; $j < $max; $j += 10**-$pre) {
            $sums->{sprintf "%.${pre}f", $i}{sprintf "%.${pre}f", $j} = sprintf "%.${pre}f", $i + $j;
        }
    }

    $first = sprintf "%.${pre}f", $first;
    $second = sprintf "%.${pre}f", $second;

    return defined $sums->{$first}{$second} ? $sums->{$first}{$second} : 'Out of range';
}

# example usage
while (1) {
    print "Please enter the first number: ";
    chomp(my $first = <STDIN>);
    print "Please enter the second number: ";
    chomp(my $second = <STDIN>);

    print 'Result: '.sum($first, $second)."\n";
}

```

This demo only works with numbers from `0`-`10` with two places of decimal precision, you can customise these values using the variables in `sum()`.
> 1 votes

# Answer
# R

Obviously you **have to** do it in R as everybody does computing in R. There is no way a serious company would consider a solution that is not based on R (apart from some trivial calculations, of course). But beware that once you start using R, you have to become R-conscious and use it in an idiomatic way. This is not just about speed (computer time is cheap these days!) but about efficient use of your own time and brains. And make sure to include nice comments in your code - you have to explain how you do things, otherwise when you may regret it later and lose all hope when trying to debug or expand your code later, in vain, needless to say. You have to be careful about formatting your answer. A true answer is useless if it is just printed out without explanations so you need an expert (read: yourself) to be present every time the software is used and an answer is computed. Sorry for harsh words but such a software is crap! Do a service to your client and format your output in a human-readable, nice and explanatory way.

And finally, surely you do not want a boring piece of software that always returns the same answer given the parameters. It is much more creative if you have an element of randomness in your life. The nice trick is also that you can switch it off if you really need it to always give the "true" (boring) answer. This switch is hidden in the code and there is no chance of finding it independently but I will reveal the secret once you transfer a modest $100000 to my account #123223323 in Ihaka Bank, Ltd.

So the code.

```
addTwo <- function(QuitAfterUse = "Nope", START = -9999){
  # This function features nice semicolon style that makes            ;
  # it clearer where the lines end.                                   ;
  # In addition, every line of the output is conveniently             ;
  # on a separate line.                                               ;
  # That makes the code easier to debug.                              ;
  # We use the unvectorized style that is common in                   ;
  # modern languages like Julia.                                      ;
  # Set the argument QuitAfterUse to "Sure!!" if you want             ;
  # the program to close R after it has finished its                  ;
  # calculations.                                                     ;
  # The code features efficient use of the magic numbers 42 and pi.   ;
  # Another bonus for advanced users is that you can start            ;
  # your computations from an arbitrary START value.                  ;
  # **** Have fun!                                                    ;
  cat("Enter the first variable (a)\n")        ;
  cat("==>")                     ;
  First <- scan(nmax=1);
  cat("\n")               ;
  cat("Enter the second variable (b)\n");
  Second <- scan(nmax=1);
  Result <- 0           ;
  for(iii in seq(START, First, as.integer(is.numeric(pi)))) {
    Result <- Result + 1      ;
  }   ;
  for(jjj in seq(START, Second, as.integer(is.numeric(42)))) {
    Result <- Result + 1                    ;
  }      ;
  CONST <- 2*START - 2     ;
  Result <- Result + CONST;
  Result <- if(TRUE | runif(1)>0.95) sample(1:(First+Second),1) else Result;
  cat("****************************\n");
  cat("****** The answer **********\n");
  cat("****************************\n");
  cat("\n");
  cat(First, "+", Second, "=", "\n");
  cat("==>", Result);
  cat("\n");
  cat("\n");
  cat("****************************\n");
  cat("***** Congratulations!!11***\n");
  cat("****************************\n");
  if(QuitAfterUse!="Nope") {
    q("yes");
  };
  return(invisible(START));
  };

```
> 1 votes

# Answer
I present to you, BogoSum, written in Java:

```
public static int sum(int a, int b) {
    java.util.Random random = new java.util.Random();
    while(true) {
        int guess = random.nextInt();
        if(guess - a == b)
            return guess;
    }
}

```
> 1 votes

# Answer
```
#!/usr/bin/env ruby

def skynet()
  # first we must input the numbers. like professional, we will input
  # from file, called numbers.txt

  # this involve first to get the size of the file.

  size = `cat numbers.txt | wc -c`.to_i;

  # now we will read each byte and place in associative array. for
  # clarity, the first byte will be at map key "bytenr1", the second
  # will be "bytenr2", etc for each byte of the file

  bytes = {};

  (1..size).each{ |index|
    bytes["bytenr#{index}"] = `dd if=numbers.txt bs=1 skip=#{index-1} count=1`;
  }

  # now we will replace the spaces with plus symbol

  fixed = {};

  (1..size).each{ |index|
    fixed["bytenr#{index}"] = bytes["bytenr#{index}"];
    fixed["bytenr#{index}"] = "+" if (bytes["bytenr#{index}"] == " ");
  };

  # finally we send this numbers to ALU driver program to perform it

  result = `echo "#{fixed.values.join}" | bc -q`;

  # the result, it's being return as string here but you can add .to_i
  # to conversion it to integer

  return result;
end

puts(skynet.inspect);

```

Notes: Does a bunch of flaky/whacky operations, such as running dd once per byte to input the file data. Also, does not actually contain the algorithm for adding the numbers, leaving that to the external program "bc", which is humourously referenced as an "ALU driver program". Also breaks if the input numbers aren't delimited exactly by one space each.
> 1 votes

# Answer
# R

Don't pollute! Use this environment-friendly approach in R.

In addition to being environment friendly, it is also very intuitive. Plus, it is the start of a new programming paradigm, chamber oriented programming. Basically, you just add things to the chamber and then remove them one by one - that's the way counting works in everyday life. Once you have mastered this basic technique, you can move on to more advanced methods.

One advantage of this technique is transparency. The function returns the used environment and you can check if has been properly emptied.

```
addTwo <- function(a,b){
  # adding two numbers
  # this environment-friendly approach works
  # with integer values from 1 to 26!
  #
  # create a new environment
  chamber <- new.env()
  # now loop through 1...a and 1...b,
  # assigning a new variable at each step
  with(chamber,  {
       for(.iii in LETTERS[1:a]) assign (.iii,.iii)
       for(.jjj in letters[1:b]) assign (.jjj,.jjj)
  }
  )
  # initialize the counter
  counter <- 0
  # remove variables from the chamber, adding
  # 1 to the counter at each step
  for(.kkk in ls(chamber)){
    counter <- counter + 1
    rm(list=.kkk, envir = chamber)
  }
  # for re-using the environment which is now empty
  # we return it together with the answer
  c(Answer = counter, ReusableEnvironment = chamber)
}

```

A question to the advanced users: which variables remain in the chamber? Why? And why aren't they counted?
> 1 votes

# Answer
Here is a way to add two numbers using inline x86 assembly in C

```
#include <stdio.h>

int sum(int n1, int n2)
{
    int result;
    __asm__ ( "addl %%ebx, %%eax;"
             : "=a" (result)
             : "a" (n1), "b" (n1));
    return result;
}

int main()
{
    printf("%d \n", sum(2, 2));
    return 0;
}

```
> 1 votes

# Answer
## PostgreSQL's plpgsql:

```
CREATE OR REPLACE FUNCTION sum(_a int, _b int)
RETURNS int AS
$BODY$
DECLARE
  i int := 0;
BEGIN
  IF _a < 0 OR _b < 0 THEN
    RAISE EXCEPTION 'Please contact our sales to get license for negative numbers version!';
  END IF;

  CREATE TEMP TABLE temp_sum (data boolean NOT NULL DEFAULT false) ON COMMIT DROP;

  INSERT INTO temp_sum SELECT generate_series(1, _a, 1)::bool;
  INSERT INTO temp_sum SELECT generate_series(1, _b, 1)::bool;

  EXECUTE 'SELECT data FROM temp_sum WHERE data=true;';
  GET DIAGNOSTICS i = ROW_COUNT;

  DROP TABLE IF EXISTS temp_sum;

  RETURN i;
END;
$BODY$ LANGUAGE plpgsql;

```

And to get result:

```
SELECT sum(1, 4);

```
> 1 votes

# Answer
## Brainfuck

Gets two integers from standard input and outputs to standard output

```
,>,[<+>-]<.

```

---

It adds the ASCII values, not the numbers themselves. Plus, only takes one digit.
> 1 votes

# Answer
Javascript and jQuery

Link to a google search page with a calculator that has the answer. Add some annoying messages to add in to the mix, just to make sure the user doesn't forget that the function is running.

```
function add(a, b) {
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("Calculating... Please wait")
    alert("An error has occured.")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    alert("Redirecting... Please wait")
    $("body").html("<a href='http://google.com/search?q=" + a.toString() + "%2B" + b.toString() + "'>Click Here</a>")
    alert("Click the link")
    alert("Don't forget that")
    alert("Don't forget it.")
    alert("You better not forget it")
    alert("Or else...")
}

```
> 1 votes

# Answer
# Perl

```
sub sumation
{
 $sring = "";
 for(0..$#_){
  $sring .= 'for(1..'."$_[$_]".'){$muchtotol[$suchsumationwow =()= (join("",@muchtotol) =~ /$$/g)] = $$}'
 }
 eval$sring;
 $suchsumationwow =()= (join("",@muchtotol) =~ /$$/g)
}

```

It's not too hard to understand. Basically, this takes the approach of taking an array, adding X,Y,Z... elements to it, and then finding the total size of the array to calculate X+Y+Z. The main twist is that it uses `$sring` and `eval` to construct a series of For loops to add the required number of elements. Also, it uses Regex to determine the size of the array.

Edit: I should mention that I tried to name my variables in a way that matches the OP's dialect.
> 0 votes

# Answer
**Bash**

```
function add() {
  curl -s http://www.bing.com/search\?q=$1%2B$2\&go=\&qs=bs\&form=QBRE\&filt=all \
    | tr '<' '\n' | grep cfap | tr '>' '\n' | tail -1
}

```
* Uses an external resource
* In a fragile manner (depending on the HTML layout, parameters, etc.)
* Probably violates the usage license while doing so
* The result cannot be used in the program, is only written on screen
> 0 votes

# Answer
# Ruby

I suggest an Object Oriented approach. The base class could be something like:

```
class Summer
  attr_accessor :a, :b

  def initialize(a, b)
    @a = a
    @b = b
  end

  def sum
    @a.coerce(@b).inject(0, &:+)
  end

end

```

And then it's just a case of creating an instance of the Summer class with the proper arguments and send it the `sum` message.
> 0 votes

# Answer
**C#**

This function handles positive *and* negative numbers. It takes a while to run but its always right!

If there is an error in the OS, compiler, or memory, it will return -1. Just be sure to check the result for -1 so you won't be blindsided by an unexpected problem!

```
 static long MyAdderFunction(int a, int b)
    {
        for (long i = long.MinValue;i<=long.MaxValue;i++) {
            if (a + b == i)
            {
                return i;
            }
        }
        //If the function has an error, it will return -1
        return -1;
    }

```
> 0 votes

# Answer
I made a LISP in Brainfuck some years ago and some Japanese guy made a good effort trying to use it to add numbers even though it didn't have numbers!. (After all, McCarthy's lisp didn't have numbers)

As a response I made a program that sums two numbers. Below is the code as written with Zozoztez primitives:

```
;; usage: ./zozotez addition.zzt or
;;        jitbf zozotez.bf < addition.zzt or
;; one anonymous function to wrap all our stuff in it
((\()

;; symbols 0 to 9 to represent digits. eg. 100 is '(1 0 0)
(:'d2clis '(0 1 2 3 4 5 6 7 8 9))

;; auxuillary function for d2c
(:'d2caux
    (\ (lis num)
       (? (= (a lis) digit)
           num
           (d2caux (d lis) (c '* num)))))

;; auxillary for church to digit
(:'c2daux
    (\ (c1 lis)
      (? c1
         (c2daux (d c1) (d lis))
         (a lis))))

;; convert church to digit
(:'c2d (\ (c1) (c2daux c1 d2clis)))

;; convert digit to church
(:'d2c (\ (digit)
   (d2caux d2clis ())))

;; convert number to church
;; '(1 0) => (() (*))
(:'n2c (\ (na acc)
   (? na
      (n2c (d na) (c (d2c (a na)) acc))
      acc)))

;; number 9 and 10
(: '9 '(* * * * * * * * *))
(:'10 '(* * * * * * * * * *))

;; print a number
(:'numprint (\ (lis)
   (? lis
      ((\()
          (p (a lis) ())
          (numprint (d lis))))
      (p '| |))))

;; returns T if cnum is above 9
(:'carry (\ (cnum 9)
   (? 9
      (? cnum
         (carry (d cnum) (d 9)))
      (? cnum T))))

;; modulus 10
(:'mod (\ (dm acc2 cnt)
  (? cnt
      (? dm
         (mod (d dm) (c '* acc2) (d cnt))
         acc2)
      (mod dm () 10))))

;; adds lists of church numerals with lsn first
(:'+c (\ (c1 c2 c3 acc)
  (?
     (? (= c1)
        (? (= c2)
           (? (= c3)
              ()
              T)
           T)
        T)
      ((\ (sum)
          (+c (d c1) (d c2) (carry sum 9) (c (c2d (mod sum () 10)) acc)))
              (+dd (a c1) (? c3 (c '* (a c2)) (a c2))))
      acc)))

;; define + to add two multi digit numbers
;; l1 and l2 are both lists with digits. eg. 123 is '(1 2 3)
(:'+ (\ (l1 l2)
   (+c (n2c l1)
       (n2c l2))))

;; test it with multiple digit implementation
(p '|123 + 928 = | ())
(numprint (+ '(1 2 3) '(9 2 8))) ; ==> prints 1051

;; end of outer anonymous lambda function
))

```

This is a highly readable Scheme variant that also operates on church numerals internally, but since Scheme has numbers it takes numbers as arguments:

```
;;; Sum two numbers
(define (sum a b)
  ;; convert to church
  (define (number->church x)
    (let loop ((x x) (acc '()))
      (if (zero? x)
          acc
          (loop (- x 1) (cons '* acc)))))

  ;; convert to number
  (define (church->number x)
    (let loop ((x x) (acc 0))
      (if (null? x)
          acc
          (loop (cdr x) (+ acc 1)))))

  ;; sum two church numbers
  (define (peano-sum c1 c2)
    (if (null? c1)
        c2
        (peano-sum (cdr c1) (cons (car c1) c2))))

  ;; do the actual sum
  (church->number
   (peano-sum (number->church a)
              (number->church b))))

```
> 0 votes

# Answer
## pureƒn

If you want to really stand out to management and peers alike, use a purely functional approach based on the lambda calculus and church numerals. Since many systems do not have a `λ` key and addition is best understood using numbers instead of cryptic letter based variables, I would suggest using a language called pureƒn

The code for the inputs would look like this:

```
0 -> [2 -1]
1 -> [1 2]
2 -> [1 (1 2)]
3 -> [1 (1 (1 2))]
4 -> [1 (1 (1 (1 2)))]

```

I am sure you see the pattern to create any number.

The program for sum is simple:

```
sum -> [1 3 (2 3 4)]

```

To add two numbers you just do:

```
[1 3 (2 3 4)] [1 (1 (1 2))] [1 (1 (1 (1 2)))]

```

and the result will be:

```
-> [1 (1 (1 (1 (1 (1 (1 2))))))]

```

People at your company familiar with functional programming may want to see `Curried` functions, this is very easy. To create a function that adds 3 to any other number just do:

```
[1 3 (2 3 4)] [1 (1 (1 2))]

```

The result will be a new function that will add 3 to any other number:

```
[2 (2 (2 (1 2 3)))]

```

Try it by using 7 as the input:

```
[2 (2 (2 (1 2 3)))] [1 (1 (1 (1 (1 (1 (1 2))))))]
-> [1 (1 (1 (1 (1 (1 (1 (1 (1 (1 2)))))))))]

```
> 0 votes

# Answer
# C++ - binary templates

Those other templates are not nearly complicated enough. Peano arithmetic is too easy. We have to use bits! And your spelling is so un creative...

```
#include <cstdio>

class wun {};
class zeroh {};

template<class... bits>
class numbur;

template<class lsb, class... msbs>
class numbur<lsb, msbs...> : public numbur<msbs...>
{};

template<>
class numbur<> {};

template<class lhs, class rhs>
class suhm;

template<class... leftoverz>
class suhm<numbur<>, numbur<leftoverz...>>
{
    public: typedef numbur<leftoverz...> rusult;
};

template<class... leftoverz>
class suhm<numbur<leftoverz...>, numbur<>>
{
    public: typedef numbur<leftoverz...> rusult;
};

template<class lsb, class... otherz>
struct cat;

template<class lsb, class... otherz>
struct cat<lsb, numbur<otherz...>>
{
    typedef numbur<lsb, otherz...> risult;
};

template<class... beezel, class... beezer>
class suhm<numbur<zeroh, beezel...>, numbur<zeroh, beezer...>>
{
    public: typedef typename cat<zeroh, typename suhm<numbur<beezel...>, numbur<beezer...>>::rusult>::risult rusult;
};

template<class... beezel, class... beezer>
class suhm<numbur<wun, beezel...>, numbur<zeroh, beezer...>>
{
    public: typedef typename cat<wun, typename suhm<numbur<beezel...>, numbur<beezer...>>::rusult>::risult rusult;
};

template<class... beezel, class... beezer>
class suhm<numbur<zeroh, beezel...>, numbur<wun, beezer...>>
{
    public: typedef typename cat<wun, typename suhm<numbur<beezel...>, numbur<beezer...>>::rusult>::risult rusult;
};

template<class... beezel, class... beezer>
class suhm<numbur<wun, beezel...>, numbur<wun, beezer...>>
{
    typedef typename suhm<numbur<wun>, numbur<beezel...>>::rusult DrewCarry;
    public: typedef typename cat<zeroh, typename suhm<DrewCarry, numbur<beezer...>>::rusult>::risult rusult;
};

template<class numbr>
struct prant;

template<>
struct prant<numbur<>>
{
    static void praaant() {
        printf("\n");
    }
};

template<class... bees>
struct prant<numbur<wun, bees...>>
{
    static void praaant() {
        printf("1");
        prant<numbur<bees...>>::praaant();
    }
};

template<class... bees>
struct prant<numbur<zeroh, bees...>>
{
    static void praaant() {
        printf("0");
        prant<numbur<bees...>>::praaant();
    }
};

typedef numbur<wun, wun, zeroh, wun> ayy;
typedef numbur<zeroh, wun, wun, zeroh, wun> beee;

int main ()
{
    prant<ayy>::praaant();
    prant<beee>::praaant();
    prant<suhm<ayy, beee>::rusult>::praaant();
    return 0;
}

```
> 0 votes

# Answer
## ANSI C

I assume skynet is a multiplatform application so you want to stay as independent from endian problems as possible. Therefor it seems sensimble to work with character buffers instead of those fancy multibyte types like integer or the like to transport basic information. Once within o´the borders of one system you can use fancier types without expecting much problems. Here is a basic implementation just to give you a general direction.

```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define element(x) {#x, x}
#define fkt_error 1
#define fkt_ok 1

typedef int (*fkt) (int argc, char *argv[], char * retBuf, unsigned retSize);

int ADD (int argc, char *argv[], char * retBuf, unsigned retSize);

typedef struct
{
    const char * name;
    fkt call;
}function;

function functionList[] =
{
    element(ADD),
};

unsigned functionListSize = sizeof(functionList) / sizeof(function);

int param_dbl(char arg[], double * p);

int main(int argc, char *argv[])
{
#ifdef _DEBUG
    char *argvmock[] = {"main","ADD","3", "7"};
    argv = argvmock;
    argc = sizeof(argvmock) / sizeof(char*);
#endif
    if(argc > 1)
    {
        unsigned i;
        for(i = 0; i < functionListSize; ++i)
        {
            if( 0 == strcmp(argv[1], functionList[i].name) )
            {
                char buffer[2000];
                functionList[i].call(argc - 1, &argv[1], buffer, 2000);
                printf("%s", buffer);
            }
        }
    }
#ifdef _DEBUG
    getchar();
#endif

}

int ADD (int argc, char *argv[], char * retBuf, unsigned retSize)
{
    if(argc != 3)
    {
        sprintf(retBuf, "%s", "insufficient argumentcount.");
        return fkt_error;
    }
    else
    {
        double a, b;
        if(fkt_ok != param_dbl(argv[1], &a))
        {
            sprintf(retBuf, "%s", "unable to parse parameter");
            return fkt_error;
        }
        if(fkt_ok != param_dbl(argv[2], &b))
        {
            sprintf(retBuf, "%s", "unable to parse parameter");
            return fkt_error;
        }
        sprintf(retBuf, "%lg", a+b);
        return fkt_ok;
    }
}

int param_dbl(char arg[], double * p)
{
    unsigned len = strlen(arg);
    if( len != sscanf(arg, "%lf", p) )
    {
        return fkt_error;
    }
    else
    {
        return fkt_ok;
    }
}

```
> 0 votes

# Answer
# C#

I'm afraid it is ***not possible*** to add two integers together :(

However, there's an easy solution!! It is possible to decrement until you find the desired result! It's a *little* slow, but if you have an AlienWare it shouldn't be a problem! Here's the code :

```
    public static int Sum(int __FirstNUMBER, int __SecondNUMBER)
    {
        Int32 _IntegerMaximalValue = Int32.MaxValue;
        Int32 _TheSum = _IntegerMaximalValue;

        while(_TheSum > __FirstNUMBER - __SecondNUMBER * -1)
        {
            Int32 _One = Int32.Parse("1");
            _TheSum = _TheSum - _One;
        }

        return _TheSum;
    }

```
> 0 votes

# Answer
# C++

```
#include <iostream>
using namespace std;

class MyInt
{
    public:
    MyInt() : b(42){}

    MyInt(int a) : b(a) {}

    MyInt operator+(int a)
    {
        return MyInt(a) + b;
    }

    MyInt operator[](MyInt a)
    {
        return a + b;
    }

    int b;
};

class addInt
{
    public:
    int operator()(MyInt a, MyInt b)
    {
        MyInt tmp = a[b];
        return *((int*)&tmp);
    }
};

int main()
{
    cout << addInt()(3,4);
}

```

It would calculate the correct result, if it was no endless recursion.
> 0 votes

# Answer
Lua:

```
function addtwonumbers(...)
    number=0
    nums={...}
    strnums=""
    strnums=table.concat(nums,":")..":"
    for s in strnums:gmatch("(%d)[:]") do
        number=number+tonumber(s)
    end
    return number
end

```
> 0 votes

# Answer
Two's complement is overrated. This uses seven's complement with eleven digits, because seven and eleven are my favorite prime numbers and should be yours too.

```
// Adds two numbers -- beware of overflow for numbers greater than (7^11 - 7^10)!
function sum(a, b) {
    // Convert to seven's complement.
    var A = toSeven(a).split('');
    var B = toSeven(b).split('');

    // Addition algorithm.
    var sum = new Array(11);
    var carry = 0;
    for (var i = 10; i >= 0; i--) {
        sum[i] = (+A[i] + +B[i] + carry) % 7;
        carry = (+A[i] + +B[i] + carry) >= 7;
    }

    // Translate negative numbers.
    if (sum[0] === 6)
        return parseInt(sum.join(''), 7) - Math.pow(7, 11);
    return parseInt(sum.join(''), 7);
}

// Converts a number to seven's complement.
function toSeven(x) {
    if (x < 0)
        return toSeven(x + Math.pow(7, 11));
    return ('00000000000' + x.toString(7)).slice(-11);
}

```
> 0 votes

# Answer
## Python

You should never name a function `sum`, that will override the built-in function, `sum()`!

Have you looked at `itertools`? Itertools is always your answer

```
import itertools
def add(a, b):
    zipped = itertools.izip_longest(str(a), str(b))
    return itertools.starmap(lambda x, y: int.__add__(int(x), int(y)), zipped)

print ''.join(itertools.imap(str, list(add(3, 4))))

```
> 0 votes

# Answer
The best way is to physically add a objects to b other objects. Then you can't go wrong. Here is a C function to do that. Note that o\[\] should be put outside the function to avoid stack overflow, because we want to use stack exchange.

```
#include<string.h>
char o[16777216];
int add(int a,int b)
{
    int c=0;
    strcpy(o,"");
    for(int i=0;i<a;i++) strcat(o,"a");
    for(int i=0;i<b;i++) strcat(o,"b");
    return strlen(o);
}

```
> 0 votes

# Answer
This is a very complicated task. I solved it using a new algorithm called Binary Column Addition. This Perl script takes the first two command line arguments and returns the sum:

```
#!/usr/bin/perl -w
use strict;
use warnings;

sub binarsum {
    my $first = $_[0];
    my $second = $_[1];

    if ($first == 0 && $second == 0) {
        return (0,0);
    }
    if (($first == 0 && $second == 1) || ($first == 1 && $second == 0)) {
        return (1,0);
    }
    if ($first == 1 && $second == 1) {
        return (1,1);
    }
}

sub tbr {
    my $first = $_[0];
    my @out = (0,0,0,0,0,0,0,0);

    my $rot = 0b00000001;

    foreach my $i (@out) {
        my $tmp = $first & $rot;

        if ($tmp == 0) {
            $i = 0;
        } else {
            $i = 1;
        }

        $rot = $rot << 1;
    }

    return @out;
}

sub fbr {
    my @in = @_;
    my $out = 0;

    foreach my $i (0..7) {
        if ($in[$i] == 1) {
            if ($i == 0) {
                $out += 1;
            }
            if ($i == 1) {
                $out += 2;
            }
            if ($i == 2) {
                $out += 4;
            }
            if ($i == 3) {
                $out += 8;
            }
            if ($i == 4) {
                $out += 16;
            }
            if ($i == 5) {
                $out += 32;
            }
            if ($i == 6) {
                $out += 64;
            }
            if ($i == 7) {
                $out += 128;
            }
        }
    }

    return $out;
}

sub sum {
    my @first = tbr($_[0]);
    my @second = tbr($_[1]);
    my @out = (0,0,0,0,0,0,0,0);
    my $overflow = 0;

    foreach my $i (0..7) {
        my $f = $first[$i];
        my $s = $second[$i];

        my @sum = binarsum($f,$s);

        if ($sum[0] == 0 && $overflow > 0) {
            $overflow--;
            $out[$i] = 1;
        }

        if ($sum[0] == 1 && $sum[1] == 0) {
            if($overflow % 2 == 0) {$out[$i] = 1;} else {$out[$i] = 0;};
        }

        if ($sum[0] == 1 && $sum[1] == 1) {
            if($overflow % 2 == 0) {$out[$i] = 0;$overflow++;} else {$out[$i] = 1};
        }
    }

    return fbr(@out);
}

print sum($ARGV[0],$ARGV[1]);

```
> 0 votes

# Answer
## C#

PS: The sum returned might not be correct depending on the input and the timing. If you think the sum is incorrect, please try to call it again until it returns correct result.

```
public static int Sum(int[] inputs) {
    return new Random().Next(inputs.Max() * 3);
}

```
> 0 votes

# Answer
This is a very complicated task. I solved it using a new algorithm called Binary Column Addition. This Perl script takes the first two command line arguments and returns the sum:

```
#!/usr/bin/perl -w
use strict;
use warnings;

sub binarsum {
    my $first = $_[0];
    my $second = $_[1];

    if ($first == 0 && $second == 0) {
        return (0,0);
    }
    if (($first == 0 && $second == 1) || ($first == 1 && $second == 0)) {
        return (1,0);
    }
    if ($first == 1 && $second == 1) {
        return (1,1);
    }
}

sub tbr {
    my $first = $_[0];
    my @out = (0,0,0,0,0,0,0,0);

    my $rot = 0b00000001;

    foreach my $i (@out) {
        my $tmp = $first & $rot;

        if ($tmp == 0) {
            $i = 0;
        } else {
            $i = 1;
        }

        $rot = $rot << 1;
    }

    return @out;
}

sub fbr {
    my @in = @_;
    my $out = 0;

    foreach my $i (0..7) {
        if ($in[$i] == 1) {
            if ($i == 0) {
                $out += 1;
            }
            if ($i == 1) {
                $out += 2;
            }
            if ($i == 2) {
                $out += 4;
            }
            if ($i == 3) {
                $out += 8;
            }
            if ($i == 4) {
                $out += 16;
            }
            if ($i == 5) {
                $out += 32;
            }
            if ($i == 6) {
                $out += 64;
            }
            if ($i == 7) {
                $out += 128;
            }
        }
    }

    return $out;
}

sub sum {
    my @first = tbr($_[0]);
    my @second = tbr($_[1]);
    my @out = (0,0,0,0,0,0,0,0);
    my $overflow = 0;

    foreach my $i (0..7) {
        my $f = $first[$i];
        my $s = $second[$i];

        my @sum = binarsum($f,$s);

        if ($sum[0] == 0 && $overflow > 0) {
            $overflow--;
            $out[$i] = 1;
        }

        if ($sum[0] == 1 && $sum[1] == 0) {
            if($overflow % 2 == 0) {$out[$i] = 1;} else {$out[$i] = 0;};
        }

        if ($sum[0] == 1 && $sum[1] == 1) {
            if($overflow % 2 == 0) {$out[$i] = 0;$overflow++;} else {$out[$i] = 1};
        }
    }

    return fbr(@out);
}

print sum($ARGV[0],$ARGV[1]);

```
> 0 votes

# Answer
**C++**

Hello,

I see that you have received only answers ment to throw you off. What you have to understand is that computers represent numbers by binary digits and so they add the numbers by adding bit by bit.

Here is how you add 2 numbers. I wrote this as clean as possible and I have commented each line so that it is easy for you to understand the code.

```
#include <cstdint>

#include <iostream>
#include <vector>
#include <type_traits>

using std::cin;
using std::cout;
using std::endl;

// type for binary digit
using bit = uint8_t;

// class to represent an integral number as a vector of binary digits
// Integral template must be an Integral type
template <class Integral, class Enable = void>
class DigitsNumber;

// class to represent an integral number as a vector of binary digits
// Integral template must be an Integral type
template <typename Integral>
class DigitsNumber<Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>{
  public:
    // the number of binary digits
    static const int kNumDigits = sizeof(Integral) * 8;

  private:
    // the vector of binary digits
    // index 0 is the index of  LSB the least significant bit
    std::vector<bit> digits = std::vector<bit>(kNumDigits);

  public:
    // default constructor, initializes to 0
    DigitsNumber();

    // copy constructor
    DigitsNumber(const DigitsNumber<Integral> &o2);
    // copy assignment
    DigitsNumber<Integral> &operator=(const DigitsNumber<Integral> &o2);

    // move constructor
    DigitsNumber(DigitsNumber<Integral> &&o2);
    // move assignment
    DigitsNumber<Integral> &operator=(DigitsNumber<Integral> &&o2);

    // constructor (and conversion) from Integral type
    DigitsNumber(Integral n);
    // conversion to Integral type
    operator Integral() const;

    // Sum
    template <class Integral>
    friend DigitsNumber<Integral> operator+(const DigitsNumber<Integral> &n1, const DigitsNumber<Integral> &n2);
};

// Sum
template <class Integral>
DigitsNumber<Integral> operator+(const DigitsNumber<Integral> &n1, const DigitsNumber<Integral> &n2);

// write to ostream
template <class Integral>
std::ostream &operator<<(std::ostream &os, const DigitsNumber<Integral> &n);

// default constructor, initializes to 0
template <class Integral>
DigitsNumber<Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>::DigitsNumber()
    : DigitsNumber<Integral>(0) {
};

// copy constructor
template <class Integral>
DigitsNumber<Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>::DigitsNumber(
      const DigitsNumber<Integral> &o2) : digits(o2.digits) {
}
// copy assignment
template <class Integral>
DigitsNumber<Integral> &DigitsNumber<Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>::operator=(
      const DigitsNumber<Integral> &o2) {
  if (this == &o2) {
    return this;
  }
  digits = o2.digits;
  return *this;
}

// move constructor
template <class Integral>
DigitsNumber<Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>::DigitsNumber(
      DigitsNumber<Integral> &&o2) : digits(std::forward<std::vector<bit> &&>(o2.digits)) {
}
// move assignment
template <class Integral>
DigitsNumber<Integral> &DigitsNumber<Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>::operator=(
      DigitsNumber<Integral> &&o2) {
  digits = std::forward<std::vector<bit> &&>(o2.digits);
  return *this;
}

// constructor (and conversion) from Integral type
template <class Integral>
DigitsNumber<Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>::DigitsNumber(Integral n) {
  for (int i = 0; i < kNumDigits; ++i) {
    digits[i] = n & 0x01;
    n >>= 1;
  }
}

// conversion to Integral type
template <class Integral>
DigitsNumber<Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>::operator Integral() const {
  Integral n = 0;
  for (int i = kNumDigits - 1; i >= 0; --i) {
    n = (n << 1) | digits[i];
  }
  return n;
}

// Full binary adder
void AddWithCarry(bit op1, bit op2, bit carry_in, bit &sum, bit &carry_out) {
  sum =  op1 ^ (op2 ^ carry_in);
  carry_out = (op2 & carry_in) | (op1 & carry_in) | (op1 & op2);

}

// sum two DigitsNumber objects
template <class Integral>
DigitsNumber<Integral> operator+(const DigitsNumber<Integral> &n1, const DigitsNumber<Integral> &n2) {
  DigitsNumber<Integral> n;
  bit carry = 0;
  bit new_carry;

  for (int i = 0; i < n.kNumDigits; ++i) {
    AddWithCarry(n1.digits[i], n2.digits[i], carry, n.digits[i], new_carry);
    carry = new_carry;
  }
  return n;
}

// write DigitsNumber to ostream
template <class Integral>
std::ostream &operator<<(std::ostream &os, const DigitsNumber<Integral> &n) {
  os << (Integral) n;
  return os;
}

// Function to add 2 numbers
template <class Integral>
Integral Sum(Integral a, Integral b) {
  DigitsNumber<Integral> da = a;
  DigitsNumber<Integral> db = b;

  return da + db;
}

int main() {
  // Basic usage example of the Sum function
  cout << Sum(3, 10) << endl;
  cout << Sum(3, -10) << endl;

  return 0;
}

```

Bullet Points:

* The class `DigitsNumber` is used to represent a number by a vector of it's binary digits.
* The function `void AddWithCarry(bit op1, bit op2, bit carry_in, bit &sum, bit &carry_out)` implements a Full Adder http://en.wikipedia.org/wiki/Adder\_(electronics)#Full\_adder for binary digits using boolean algebra. That's how computers do it.
> 0 votes

# Answer
# jQuery / Backbone.js

Due to the complex nature of this problem, I will be employing high-level jQuery techniques. In addition to this, the function cannot be properly managed without a robust MVC-based architecture to handle server-side validation.

```
function sum(a, b, callback) {

  callback = callback || function(){};

  // As polluting the global namespace
  // would be unspeakable, it is best
  // advised to wrap all of your
  // code in 3 (three) self-executing
  // anonymous functions.
  function(a2, b2){
    function(a3, b3){
      function(a4, b4){

        // Run an initial validation on the numbers
        // to be sure we are actually dealing with numbers.
        // If we weren't, that would be very bad, and might
        // end up with....
        // NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN Watman!
        var NumberValidator = function(number) {

          var valid = false;

          if (!isNaN(number)) {

            if (number !== undefined) {

              if  (String(number).trim() !== '') {

                if (String(number).trim().toLowerCase().substr(0, 18) !== 'GREEN-EGGS-AND-HAM') {

                  // Okay, we're really good now.
                  valid = true;

                };

              };

            };

          };

          return valid;

        };

        // Set constants to make validity clear.
        var VALID_STATE_VALID = true;
        var VALID_STATE_INVALID = false;

        var aNumberIsValid, bNumberIsValid;
        aNumberIsValid = NumberValidator(a4);
        bNumberIsValid = NumberValidator(b4);

        // If we are invalid, ensure the caller of the function knows.
        if (aNumberIsValid === VALID_STATE_VALID && bNumberIsValid === VALID_STATE_VALID) {

          var responseMessage = {
            response: 'ERROR',
            data: 'Could not validate due to an invalidation of VALID_STATE_VALID'),
            message: 'INVALID_STATE_VALID',
          };

          callback(responseMessage);

        };

        // Fire the numbers off to a more complex server-side
        // validation service that ensures we are dealing with real
        // numbers and not somebody's trickery.
        var NumberIntegrityModel = Backbone.Model.extend({

          url: '/number-validation-service/transaction-persistor/execute',

          defaults: {
            a: false,
            b: false,
            valid: false,
          },

          parse: function(response) {

            if (response[0][0][1][6][5].response.transactionState !== 'ERROR') {

              return response[0][0][1][6][5].payload.transaction.results;
            }
          },

        });

        var numberIntegrityModel = new NumberIntegrityModel();

        numberIntegrityModel.on('save', function(){

          var valid = this.get('valid');

          if (val !== true) {

            var responseMessage = {
              response: 'ERROR',
              data: 'There is something seriously sketchy going on with those numbers. Investigate.'),
              message: 'INVALID_INTEGRITY_CHECK',
            };

            callback(responseMessage);

          } else {

            // Okay, we're actually dealing with two
            // perfectly valid numbers. Now let's get to the
            // number crunching.
            var varianceSpectrum = .5;
            var result = (a4 * (Math.floor(Math.sqrt(64) + (varianceSpectrum * (varianceSpectrum/2))) - (Math.pow(2, 3) - 1)) + b4);

            // I think this part is right.
            try() {
              'NaNNaNNaNNaNNaNNaN';
            } catch(e) {

              // Yeah, it must be. Works every time.
              callback({
                response: 'SUCCESS',
                data: result,
                message: 'LIKE_A_CHARM',
              });

            };

          };

        });

        numberIntegrityModel.save({
          a: a4,
          b: b4
        });

      }(a3, b3);
    }(a2, b2);
  }(a, b);
}

```

Not only is the architecture of my solution a jaw-dropping aesthetic, the implementation could not be bested.

```
sum(4, 5, function(result) {

  if (result.response == 'SUCCESS') {

    var sum = result.data;
    console.log(sum);
  }
});

```
> 0 votes

# Answer
## C++

```
#include <iostream>
#include <stdio.h>
#include <string.h>

std::string sum(std::string n1,std::string n2)
{
    int r1=0,d1,p;
    int size2 = n2.size()-1;
    char* ar = new char [size2+2];
    memset(ar,'0',size2+2);
    p= size2+1;

    for(int i= n1.size()-1; i >=0 ; --i)
    {
        d1 = n2.at(size2) + n1.at(i) - 96 + r1;
        ar[p--] += d1 % 10;
        r1 = d1 / 10;
        --size2;
    }

    for(int i=size2;i >=0;--i)
    {
        d1 = n2.at(i) + r1 - 48;
        ar[p--] += d1 % 10;
        r1 = d1 / 10;
    }

    ar[p--] += r1;

    std::string res = std::string(ar);
    delete [] ar;

    return res;
}

int main ()
{

    std::string n1;
    std::string n2;

    std::cout<< "First Number :" ;
    std::cin>> n1;
    std::cout<< "Second Number :" ;
    std::cin>> n2;

    if(n1.length()<n2.length())
        std::cout<< "Sum:" sum(n1,n2);
    else
        std::cout<< "Sum:" sum(n2,n1);

  return 0;
}

```
> 0 votes

# Answer
# Bash

Add the following lines to a file called `.bashrc` in your home directory.

```
add() {
    buffer=`mktemp -t addbuffer`
    seq $1 > $buffer
    yes | head -n $2 >> $buffer
    wc $buffer | sed -E 's/\s*([0-9]+).*/\1/'
    rm -f $buffer
}

```

**Now restart your system so that the changes can take effect.**

Once you have rebooted you can do for instance `add 1 2` and you will presented the answer `3`.
> 0 votes

# Answer
# R (increment-decrement approach)

Let's first define the increment and decrement functions:

```
"-<-"<-function(x, value) x <- x-value
"+<-"<-function(x, value) x <- x+value

```

The first will be used to decrement a variable's value, and the second to increment it. Ok so far so good. Now the trick is to increment B and decrement A until very little is left.

```
addTwo <- function(A, B, STEP = 1) {
   while(A>=1) -A <- STEP -> + B
   c(sum = B, remainder= A)
   }

```

This approach works with all *positive* numbers. For those who care: the little something that remains in A after decrementing it, is also returned for future use. If you want, you can re-run the function with a smaller `STEP` (maybe start with 0.1) until the returned `remainder` is so small that you don't care any more.
> 0 votes

# Answer
## Python

This is the only obvious way to do it:

```
def add2nums(n1, n2):
    ''' # is the symbol for number '''
    return len(''.join('#' for _ in range(n1)) + ''.join('#' for _ in range(n2)))

```
> 0 votes

# Answer
PYTHON

```
def sum(list):
    total = 0
    for i in list:
        total += i
    return total

```
> 0 votes

# Answer
**C++**

```
#include <iostream>
using namespace std;
int main()
{
  int a, b, sum;
  cin >> a >> b;
  sum = a;
  for(int i = 0; i < b; i++)
  {sum++;}
  cout << sum << endl;
  return 0;
}

```

This doesn't work on doubles, though.
> 0 votes

---
Tags: popularity-contest, code-trolling
---