42
votes
\$\begingroup\$

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.

\$\endgroup\$

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

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

locked by Doorknob May 11 '14 at 22:35

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

Read more about locked posts here.

  • 31
    \$\begingroup\$ You can use my lightweight jQuery plugin: $.sum=function(a,b){return a+b};. \$\endgroup\$ – Blender Dec 28 '13 at 13:51
  • 5
    \$\begingroup\$ I knew I'd get a jQuery reference sometime \$\endgroup\$ – scrblnrd3 Dec 28 '13 at 13:51
  • 5
    \$\begingroup\$ Brilliant English :p \$\endgroup\$ – Martijn Courteaux Dec 28 '13 at 17:39
  • 5
    \$\begingroup\$ Question suggestion (not sure if it's any good): "GUISE HALP, I need a fast algorithm to generate bitcoin blocks!!!!! It's super urgent!" \$\endgroup\$ – user11485 Dec 28 '13 at 18:42
  • 5
    \$\begingroup\$ These answers are quite involved. I suggest opening a connection to your database and issuing 'SELECT ' + a + ' + ' + b + ';'. It's simple and understandable. \$\endgroup\$ – Nick Chammas Dec 28 '13 at 20:57

75 Answers 75

69
votes
\$\begingroup\$

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

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

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;

}
\$\endgroup\$
  • 3
    \$\begingroup\$ Reading this made my eyes bleed. +1 \$\endgroup\$ – user11485 Dec 28 '13 at 17:05
  • \$\begingroup\$ What does it return? I'm not really into running this. \$\endgroup\$ – Martijn Courteaux Dec 28 '13 at 17:17
  • \$\begingroup\$ For those that don't want to run aVeryLargeNumber(): It returns 1. (I'll remove this if the OP pings me.) \$\endgroup\$ – apnorton Dec 28 '13 at 19:14
2
votes
\$\begingroup\$

a function that inputs and returns their sum

Lua

function f()
  local theirsum = io.read"*n"
  return theirsum
end
\$\endgroup\$
40
votes
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Can write or flush throw? It looks to me like you should move flush into each loop, and wrap the whole thing in a try-catch to retry the write if it or the flush fails. \$\endgroup\$ – Anton Golov Dec 28 '13 at 22:51
  • 3
    \$\begingroup\$ I suggest you use a writer with the default character encoding instead of a stream. Then it can potentially break on a system for which your selected character encodes into multiple bytes. \$\endgroup\$ – Buhb Dec 29 '13 at 18:41
19
votes
\$\begingroup\$

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);
   }
}
\$\endgroup\$
  • 12
    \$\begingroup\$ Replace return sum(a-number, b+number); with return sum(sum(a,-number), sum(b,number));. You got to eat your own dog food right? \$\endgroup\$ – emory Dec 28 '13 at 16:13
  • \$\begingroup\$ @emory: That will not work, I think. \$\endgroup\$ – Martijn Courteaux Dec 28 '13 at 17:18
  • \$\begingroup\$ @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. \$\endgroup\$ – emory Dec 28 '13 at 17:20
  • \$\begingroup\$ @emory: Okay, I tested it and it apparently works. Great :) \$\endgroup\$ – Martijn Courteaux Dec 28 '13 at 17:37
3
votes
\$\begingroup\$

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
\$\endgroup\$
21
votes
\$\begingroup\$

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)

\$\endgroup\$
  • 2
    \$\begingroup\$ Would you mind telling me what IDE you are using in the screenshot? Visual studio doesn't give me that syntax highlighting \$\endgroup\$ – Joe the Person Dec 29 '13 at 16:48
  • 1
    \$\begingroup\$ @JoethePerson: That's not an IDE, just an overpriced text editor called "Sublime Text". \$\endgroup\$ – Apache Dec 29 '13 at 16:55
  • 1
    \$\begingroup\$ @JoethePerson Like Shiki said its a text editor that's a bit more fancy and it does have a free version, see here: sublimetext.com. \$\endgroup\$ – C1D Dec 29 '13 at 17:31
  • \$\begingroup\$ @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. \$\endgroup\$ – C1D Dec 29 '13 at 17:31
2
votes
\$\begingroup\$

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;
    }
}
\$\endgroup\$
3
votes
\$\begingroup\$

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;
       }
}
\$\endgroup\$
1
vote
\$\begingroup\$

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

\$\endgroup\$
0
votes
\$\begingroup\$

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.

\$\endgroup\$
29
votes
\$\begingroup\$

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.

\$\endgroup\$
24
votes
\$\begingroup\$

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.

\$\endgroup\$
60
votes
\$\begingroup\$

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.

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

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;
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Trolling 1: this actually works and is a valid way of adding numbers - it's not far off how hardware does it. However, the countdown uses subtract, so it's not a purely bitwise solution at all. Trolling 2: requirement to specify a precision in bits; incorrect precision results in nonsense answers. Trolling 3: "Downto" operator. \$\endgroup\$ – Riot Dec 28 '13 at 16:57
  • \$\begingroup\$ Add some inline assembler! \$\endgroup\$ – Kiruse Dec 28 '13 at 23:39
14
votes
\$\begingroup\$

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

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.

\$\endgroup\$
  • 3
    \$\begingroup\$ Note to OP: you can probably avoid the EXTRA DIMENTIONAL RIFT, but you'd then have to play with quantum physics, and you don't wanna do that. \$\endgroup\$ – user11485 Dec 28 '13 at 17:34
4
votes
\$\begingroup\$

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.

\$\endgroup\$
2
votes
\$\begingroup\$

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;
}
\$\endgroup\$
1
vote
\$\begingroup\$

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.

\$\endgroup\$
13
votes
\$\begingroup\$

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.

\$\endgroup\$
  • 2
    \$\begingroup\$ I just wanted to give this answer. IMAO this one and the sleepadd one are by far the best answers, since the others are needlessly complex. These instead are still completely useless but brief and elegant. It's too easy (hence boring) to make them useless by adding random complexity. \$\endgroup\$ – o0'. Dec 29 '13 at 13:23
  • 1
    \$\begingroup\$ The reasoning is flawless! \$\endgroup\$ – recursion.ninja Jan 2 '14 at 19:30
  • \$\begingroup\$ 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 \$\endgroup\$ – o0'. Jan 4 '14 at 11:53
  • \$\begingroup\$ @Lohoris - Yes, Yes it should. Fixed \$\endgroup\$ – Haedrian Jan 4 '14 at 13:08
1
vote
\$\begingroup\$

  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.

\$\endgroup\$
4
votes
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ I definitely see a theme in your answers. +Trolling points since this requires hadoop to work, and fails very messily if $HADOOP_HOME is unset. \$\endgroup\$ – Riot Dec 29 '13 at 3:12
7
votes
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Wow. Such doge. Very upvote. \$\endgroup\$ – Marc Claesen Jan 2 '14 at 22:12
0
votes
\$\begingroup\$

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
\$\endgroup\$
1
vote
\$\begingroup\$

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.

\$\endgroup\$
0
votes
\$\begingroup\$

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.

\$\endgroup\$
1
vote
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Can you spot all the subtle bugs here? \$\endgroup\$ – Michael Hampton Dec 28 '13 at 20:18
1
vote
\$\begingroup\$

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])
\$\endgroup\$
  • \$\begingroup\$ "Passing pointers is more efficient in Python" Very nice. \$\endgroup\$ – Josh Caswell Dec 28 '13 at 21:17
0
votes
\$\begingroup\$

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;
    }
\$\endgroup\$

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