How do I write an adding function?

42

9

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.

scrblnrd3

Posted 2013-12-28T13:40:52.060

Reputation: 1 554

Question was closed 2014-05-07T12:42:24.353

31You can use my lightweight jQuery plugin: $.sum=function(a,b){return a+b};. – Blender – 2013-12-28T13:51:04.570

5I knew I'd get a jQuery reference sometime – scrblnrd3 – 2013-12-28T13:51:41.270

If you don't use jQuery, you don't know programming. – None – 2013-12-28T17:30:34.500

5Brilliant English :p – Martijn Courteaux – 2013-12-28T17:39:22.110

5Question suggestion (not sure if it's any good): "GUISE HALP, I need a fast algorithm to generate bitcoin blocks!!!!! It's super urgent!" – None – 2013-12-28T18:42:38.860

Some people are using subtraction in their answers below. But, if we allow use of the binary -, then suddenly the OP should realize that an "ok" solution is: result = a - (-b), baffling our obfuscation attempts. – apnorton – 2013-12-28T19:21:25.147

5These answers are quite involved. I suggest opening a connection to your database and issuing 'SELECT ' + a + ' + ' + b + ';'. It's simple and understandable. – Nick Chammas – 2013-12-28T20:57:58.757

Is the trolled solution supposed to return the correct value? – jscs – 2013-12-28T21:00:12.390

@JoshCaswell It is. However, the correct answer is up to your interpretation. Goal of these code-trolling tagged questions is to give hilarious and hopefully useless answers that could still be marked as accepted. For more info, follow the linked Wiki article the OP gave... – Kiruse – 2013-12-28T23:25:23.873

Is there already a solution using AppleScript to call Spotlight to do the operation? – o0'. – 2013-12-29T13:49:26.537

I personally thought the english in the original was quite fitting... – Camilo Martin – 2013-12-29T20:36:38.493

I thought so too – scrblnrd3 – 2013-12-29T20:53:36.103

Damn – too late. I had a solution using bitcoin-wallets. – Fabian Zeindl – 2014-01-03T19:57:30.063

@FabianZeindl well you can post it, you might get some votes – scrblnrd3 – 2014-01-03T20:29:42.867

Write a python script that can generate another python script which contains a function doing something like if args == [1,2]: return 3. – yegle – 2014-02-17T01:16:46.020

(C#) ```int Sum (ref int a, ref int b) { var l = new List<int>() { a, b, a + b }; l.Sort((i, j) => random.Next(-1, 1));

a = l[0]; b = l[1]; return l[2]; }``` You will never know where I will return the sum. – Fabricio – 2014-05-07T15:52:33.067

Code-trolling is in the process of being removed, as per the official stance. This question is very highly voted with many answers, many of which are highly voted, and even though it recieved over 50% "delete" votes on the poll, it only did by about 12%. Therefore, I am locking it for historical significance.

– Doorknob – 2014-05-11T22:35:40.593

Answers

69

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

ProgramFOX

Posted 2013-12-28T13:40:52.060

Reputation: 8 017

11i -= -1. Very creative. I already reached the vote limit today, but I will upvote your answer as soon as I can. – Victor Stafusa – 2013-12-28T16:20:00.300

As long as you insist that anything other than 6755 & 1436 is undefined behavior, despite OP's perception that most numbers seem to work... – Trojan – 2013-12-29T02:03:15.347

What is the meaning of '=>'? – Ilya Gazman – 2013-12-29T14:01:28.487

2@Babibu I have never written a line of C# in my life but this is almost certainly a lambda expression. – thwd – 2013-12-29T14:39:24.253

@Babibu: tomwilde is right, it's a lambda expression. – ProgramFOX – 2013-12-29T17:31:15.370

I suggest putting the "real answer" into a quotation (as if you were quoting and commenting the imaginary answer to the imaginary question of the challenge). This makes clearer what exactly is part of the trolling answer and what isn't. – Bakuriu – 2013-12-30T20:04:02.343

@Bakuriu: Done. – ProgramFOX – 2013-12-31T09:51:17.693

3uh oh, var x = Sum(0, 4) DivideByZeroException. – Phillip Scott Givens – 2014-01-06T18:42:05.307

60

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.

Riot

Posted 2013-12-28T13:40:52.060

Reputation: 4 639

5Trolling 1: it works but it's stupidly slow, using the system timer to wait for the total time. Therefore larger numbers take linearly longer to add. Trolling 2: it even works for floating point, but the answers are always off by a small margin. Trolling 3: gratuitous and unnecessary use of grep, cut and tr. Trolling 4: any totals over 60 (seconds) are not handled correctly. – Riot – 2013-12-28T16:26:25.430

Lossy. How "lame". hahahaha jokes only I (and a couple of others) understand – None – 2013-12-28T17:50:50.740

4@Shingetsu: what, you're saying nobody else has heard of mp3 codecs? :P – Riot – 2013-12-28T18:00:24.153

7I'm saying very few people actually make the association. Lame IS lame though. Vorbis master race. – None – 2013-12-28T18:02:14.690

7+1 for massively off-topic audio encoder wars diatribe :) – Riot – 2013-12-28T18:03:43.633

1I believe my Bash-Hadoop version below is much more powerful and scalable!!!!1!!eleven! But I must say, I really love your version, sleepadd is great! +1 – Has QUIT--Anony-Mousse – 2013-12-28T19:44:44.853

Pfff everybody knows RMVBs rule the show. – Camilo Martin – 2013-12-29T02:25:50.773

1This is very cool and elegant! – o0'. – 2013-12-29T13:20:39.140

Now make an audio encoder which is only using SleepAdd for its additions. And see if it will beat Charles Babbage's machine in either speed or precision. – nitro2k01 – 2013-12-30T18:40:33.653

1Hey, even Babbage's Engine didn't unpredictably add random floating point increments like this does :) – Riot – 2013-12-30T20:34:12.650

1I love how 1.5 + 0.5 is 2.001. – Charlie – 2014-01-02T03:38:49.653

40

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.

Martijn Courteaux

Posted 2013-12-28T13:40:52.060

Reputation: 759

1Can write or flush throw? It looks to me like you should move flush into each loop, and wrap the whole thing in a try-catch to retry the write if it or the flush fails. – Anton Golov – 2013-12-28T22:51:45.800

3I suggest you use a writer with the default character encoding instead of a stream. Then it can potentially break on a system for which your selected character encodes into multiple bytes. – Buhb – 2013-12-29T18:41:11.373

33

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

mniip

Posted 2013-12-28T13:40:52.060

Reputation: 9 396

2+1 although it feels too readable for code trolling... – Marc Claesen – 2014-01-02T22:09:26.133

29

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.

Petr Pudlák

Posted 2013-12-28T13:40:52.060

Reputation: 4 272

24

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.

fNek

Posted 2013-12-28T13:40:52.060

Reputation: 341

21

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

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

STEP ONE - TELNET Server

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

Lets start off with the basic telnet server:

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

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

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

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

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

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

STEP TWO - summm

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

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

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

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

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

C1D

Posted 2013-12-28T13:40:52.060

Reputation: 590

2Would you mind telling me what IDE you are using in the screenshot? Visual studio doesn't give me that syntax highlighting – Joe the Person – 2013-12-29T16:48:34.420

1@JoethePerson: That's not an IDE, just an overpriced text editor called "Sublime Text". – Apache – 2013-12-29T16:55:14.773

1

@JoethePerson Like Shiki said its a text editor that's a bit more fancy and it does have a free version, see here: http://www.sublimetext.com/.

– C1D – 2013-12-29T17:31:22.520

@Shiki, I agree with you and I downloaded LightTable just a few days ago but I haven't opened it yet because I've been pretty busy. – C1D – 2013-12-29T17:31:53.913

19

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

planetguy32

Posted 2013-12-28T13:40:52.060

Reputation: 411

12Replace return sum(a-number, b+number); with return sum(sum(a,-number), sum(b,number));. You got to eat your own dog food right? – emory – 2013-12-28T16:13:37.607

@emory: That will not work, I think. – Martijn Courteaux – 2013-12-28T17:18:22.080

@MartijnCourteaux The program has a dangerous flaw - it is a blatant troll. If someone were to ask what is b+number, then it would be obvious the whole method is unnecessary. Better to obfuscate that. Plus it will make it even slower. – emory – 2013-12-28T17:20:26.863

@emory: Okay, I tested it and it apparently works. Great :) – Martijn Courteaux – 2013-12-28T17:37:56.680

14

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

Xodarap

Posted 2013-12-28T13:40:52.060

Reputation: 241

Doesn't work with python3 @ Ubuntu – s3lph – 2013-12-29T15:07:08.007

1@the_Seppi It works perfectly well. Just add from functools import reduce for python3. – Bakuriu – 2013-12-30T20:07:12.200

14

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.

user11485

Posted 2013-12-28T13:40:52.060

Reputation:

3Note to OP: you can probably avoid the EXTRA DIMENTIONAL RIFT, but you'd then have to play with quantum physics, and you don't wanna do that. – None – 2013-12-28T17:34:53.067

13

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.

Haedrian

Posted 2013-12-28T13:40:52.060

Reputation: 361

2I just wanted to give this answer. IMAO this one and the sleepadd one are by far the best answers, since the others are needlessly complex. These instead are still completely useless but brief and elegant. It's too easy (hence boring) to make them useless by adding random complexity. – o0'. – 2013-12-29T13:23:08.447

1The reasoning is flawless! – recursion.ninja – 2014-01-02T19:30:07.520

Shouldn't it be ++a instead of a++? (Edits must be at least 6 characters; is there something else to improve in this post?) stupid stupid stupid stupid SO – o0'. – 2014-01-04T11:53:01.500

@Lohoris - Yes, Yes it should. Fixed – Haedrian – 2014-01-04T13:08:49.753

9

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

Riot

Posted 2013-12-28T13:40:52.060

Reputation: 4 639

1Trolling 1: this actually works and is a valid way of adding numbers - it's not far off how hardware does it. However, the countdown uses subtract, so it's not a purely bitwise solution at all. Trolling 2: requirement to specify a precision in bits; incorrect precision results in nonsense answers. Trolling 3: "Downto" operator. – Riot – 2013-12-28T16:57:59.943

Add some inline assembler! – Kiruse – 2013-12-28T23:39:48.947

8

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;

}

scrblnrd3

Posted 2013-12-28T13:40:52.060

Reputation: 1 554

3Reading this made my eyes bleed. +1 – None – 2013-12-28T17:05:23.610

What does it return? I'm not really into running this. – Martijn Courteaux – 2013-12-28T17:17:15.373

For those that don't want to run aVeryLargeNumber(): It returns 1. (I'll remove this if the OP pings me.) – apnorton – 2013-12-28T19:14:56.950

7

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.

shiona

Posted 2013-12-28T13:40:52.060

Reputation: 2 889

1Wow. Such doge. Very upvote. – Marc Claesen – 2014-01-02T22:12:51.930

6

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

Dancrumb

Posted 2013-12-28T13:40:52.060

Reputation: 163

5

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

user253751

Posted 2013-12-28T13:40:52.060

Reputation: 818

This is my favourite. :D – Jeroen – 2014-05-06T19:32:15.557

4

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.

Martijn Courteaux

Posted 2013-12-28T13:40:52.060

Reputation: 759

4

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.

Has QUIT--Anony-Mousse

Posted 2013-12-28T13:40:52.060

Reputation: 151

1I definitely see a theme in your answers. +Trolling points since this requires hadoop to work, and fails very messily if $HADOOP_HOME is unset. – Riot – 2013-12-29T03:12:46.230

4

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

Kroltan

Posted 2013-12-28T13:40:52.060

Reputation: 517

4

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/

David

Posted 2013-12-28T13:40:52.060

Reputation: 141

But what if you need to count over 10? I don't have 3 hands! – AJMansfield – 2014-05-06T23:52:19.867

Hotfix:Use feet, you can do that up to 20. Cheers, david. – David – 2014-05-11T08:39:56.780

3

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

Timtech

Posted 2013-12-28T13:40:52.060

Reputation: 12 038

3

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

emory

Posted 2013-12-28T13:40:52.060

Reputation: 989

3

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.

jscs

Posted 2013-12-28T13:40:52.060

Reputation: 900

2

a function that inputs and returns their sum

Lua

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

mniip

Posted 2013-12-28T13:40:52.060

Reputation: 9 396

2

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

Victor Stafusa

Posted 2013-12-28T13:40:52.060

Reputation: 8 612

2

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

Shoe

Posted 2013-12-28T13:40:52.060

Reputation: 657

2

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

Gari BN

Posted 2013-12-28T13:40:52.060

Reputation: 624

Add language name – Wasi – 2013-12-30T19:18:48.310

2

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

Abhijit

Posted 2013-12-28T13:40:52.060

Reputation: 2 841

2

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

Fez Vrasta

Posted 2013-12-28T13:40:52.060

Reputation: 1 078

1

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

Kyle Kanos

Posted 2013-12-28T13:40:52.060

Reputation: 4 270

1

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.

Dakeyras

Posted 2013-12-28T13:40:52.060

Reputation: 111

1

  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.

Has QUIT--Anony-Mousse

Posted 2013-12-28T13:40:52.060

Reputation: 151

1

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.

Vatine

Posted 2013-12-28T13:40:52.060

Reputation: 161

1

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.

Michael Hampton

Posted 2013-12-28T13:40:52.060

Reputation: 151

Can you spot all the subtle bugs here? – Michael Hampton – 2013-12-28T20:18:38.873

1

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

Guy Sirton

Posted 2013-12-28T13:40:52.060

Reputation: 551

"Passing pointers is more efficient in Python" Very nice. – jscs – 2013-12-28T21:17:30.413

1

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

quietmint

Posted 2013-12-28T13:40:52.060

Reputation: 204

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. – quietmint – 2013-12-29T02:23:41.703

1

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

Alex J

Posted 2013-12-28T13:40:52.060

Reputation: 111

1

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!

o0'.

Posted 2013-12-28T13:40:52.060

Reputation: 115

1

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.

Luffy

Posted 2013-12-28T13:40:52.060

Reputation: 111

1

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.

Pål GD

Posted 2013-12-28T13:40:52.060

Reputation: 383

1

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

}

MrBackend

Posted 2013-12-28T13:40:52.060

Reputation: 386

1

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

Dom Hastings

Posted 2013-12-28T13:40:52.060

Reputation: 16 415

1

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

lebatsnok

Posted 2013-12-28T13:40:52.060

Reputation: 383

1

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

James Hagborg

Posted 2013-12-28T13:40:52.060

Reputation: 61

1

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

Andrei

Posted 2013-12-28T13:40:52.060

Reputation: 11

1

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?

lebatsnok

Posted 2013-12-28T13:40:52.060

Reputation: 383

1

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

kyle k

Posted 2013-12-28T13:40:52.060

Reputation: 409

1

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

raspi

Posted 2013-12-28T13:40:52.060

Reputation: 121

1

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.

Timtech

Posted 2013-12-28T13:40:52.060

Reputation: 12 038

1

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...")
}

Potassium Ion

Posted 2013-12-28T13:40:52.060

Reputation: 191

0

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.

PhiNotPi

Posted 2013-12-28T13:40:52.060

Reputation: 26 739

0

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

Christopher Creutzig

Posted 2013-12-28T13:40:52.060

Reputation: 383

0

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.

steenslag

Posted 2013-12-28T13:40:52.060

Reputation: 2 070

0

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

poke

Posted 2013-12-28T13:40:52.060

Reputation: 221

0

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

Sylwester

Posted 2013-12-28T13:40:52.060

Reputation: 3 678

0

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

dansalmo

Posted 2013-12-28T13:40:52.060

Reputation: 8 901

0

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

Dan

Posted 2013-12-28T13:40:52.060

Reputation: 101

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

Johannes

Posted 2013-12-28T13:40:52.060

Reputation: 199

what? Too useful? :) – Johannes – 2013-12-31T01:48:11.930

0

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

Pierre-Luc Pineault

Posted 2013-12-28T13:40:52.060

Reputation: 331

0

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.

user2859193

Posted 2013-12-28T13:40:52.060

Reputation: 151

0

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

Mitchell

Posted 2013-12-28T13:40:52.060

Reputation: 11

0

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

Casey Chu

Posted 2013-12-28T13:40:52.060

Reputation: 1 661

0

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

TerryA

Posted 2013-12-28T13:40:52.060

Reputation: 171

0

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

user21820

Posted 2013-12-28T13:40:52.060

Reputation: 101

0

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

craftext

Posted 2013-12-28T13:40:52.060

Reputation: 51

0

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

tia

Posted 2013-12-28T13:40:52.060

Reputation: 745

0

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

craftext

Posted 2013-12-28T13:40:52.060

Reputation: 51

0

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.

bolov

Posted 2013-12-28T13:40:52.060

Reputation: 465

0

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

dthree

Posted 2013-12-28T13:40:52.060

Reputation: 101

0

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

kjk

Posted 2013-12-28T13:40:52.060

Reputation: 9

0

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.

daniero

Posted 2013-12-28T13:40:52.060

Reputation: 17 193

0

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.

lebatsnok

Posted 2013-12-28T13:40:52.060

Reputation: 383

0

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

dansalmo

Posted 2013-12-28T13:40:52.060

Reputation: 8 901

0

PYTHON

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

SHADOWCOW13

Posted 2013-12-28T13:40:52.060

Reputation: 1

How does this code troll the OP? – luser droog – 2014-01-03T06:10:56.887

0

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.

zscoder

Posted 2013-12-28T13:40:52.060

Reputation: 101