# How do I write an adding function? [closed]

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

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

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

• You can use my lightweight jQuery plugin: $.sum=function(a,b){return a+b};. Dec 28, 2013 at 13:51 • I knew I'd get a jQuery reference sometime Dec 28, 2013 at 13:51 • Brilliant English :p Dec 28, 2013 at 17:39 • Question suggestion (not sure if it's any good): "GUISE HALP, I need a fast algorithm to generate bitcoin blocks!!!!! It's super urgent!" – user11485 Dec 28, 2013 at 18:42 • These answers are quite involved. I suggest opening a connection to your database and issuing 'SELECT ' + a + ' + ' + b + ';'. It's simple and understandable. Dec 28, 2013 at 20:57 ## 75 Answers 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. ## 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. 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. # 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.

• Can you spot all the subtle bugs here? Dec 28, 2013 at 20:18

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])
• "Passing pointers is more efficient in Python" Very nice.
– jscs
Dec 28, 2013 at 21:17

# 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);
}
• Essentially, each input value, in turn, is incremented/decremented until it reaches zero. As the base case returns zero, all other zeros in the function have been replaced with a recursive call. The fact that is a valid JavaScript identifier is just bonus. Dec 29, 2013 at 2:23

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;

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
{

/// <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);
}

return result;
}
}

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

/// <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);
}
}
}

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!

C++ Linux

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

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.

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.

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

}

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

# 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().

}

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

Bash

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

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

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:

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

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

## 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[] =
{
};

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

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

int main(int argc, char *argv[])
{
#ifdef _DEBUG
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;
}
}
• what? Too useful? :) Dec 31, 2013 at 1:48

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

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

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

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

int main()
{
}

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

Lua:

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