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. More info: help center.

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

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

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);
}
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – quietmint Dec 29 '13 at 2:23
1
vote
\$\begingroup\$

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

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!

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

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.

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

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.

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

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

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

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

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

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

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

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

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?

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

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

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

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.

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

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...")
}
\$\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\$
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\$
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\$
0
votes
\$\begingroup\$

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

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

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;
    }
}
\$\endgroup\$
  • \$\begingroup\$ what? Too useful? :) \$\endgroup\$ – Johannes Dec 31 '13 at 1:48
0
votes
\$\begingroup\$

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)))))))))]
\$\endgroup\$
0
votes
\$\begingroup\$

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

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.

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

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

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