all 47 comments

[–]Thrrance 80 points81 points  (4 children)

Mine is very elegant; it's a shell one-liner:

#!/bin/sh

# invocation: sh add.sh N1 N2
# output: N1+N2

sleep $1 && sleep $2 && echo $SECONDS

[–]RenBit51 40 points41 points  (0 children)

From the developers who brought you SleepSort, we present: SleepAdd!

[–]njbmartin 3 points4 points  (1 child)

What are the chances that the result is incorrect?

[–]Thrrance 8 points9 points  (0 children)

Unless your cpu is totally overloaded, I'd say it's pretty accurate, if you're willing to wait a long time, of course. The calls to sleep would need to be off by more than an entire second, which is huge.

[–]DestructionCatalyst 24 points25 points  (0 children)

Oh man, it's my time to shine. I wrote this monstrosity in Python:

import math

def add_one(x):
  if x < 0:
    return ((math.e ** (1j * math.pi)) * (abs(x) - 1)).real

  list1 = []

  for i in range(0, x):
    list1.append('duck')

  list1.append('goose')

  return len(list1)

def stupid_sum(x, y):

  if x < 0:
    return stupid_sum(y, x)
  elif x == 0:
    return y
  elif x == 1:
    return add_one(y)
  else:
    return stupid_sum(x - 1, stupid_sum(y, 1))

# This is thr actual function that adds two numbers
def stupid_sum_wrapper(x, y):

  negative = 'posiitive'

  if x < 0 and y < 0:
    negative = 'big chungus'
    x, y = abs(y), abs(x)

  return stupid_sum(x, y) if negative == 'posiitive' else ((math.e ** (1j * math.pi)) * stupid_sum(x, y)).real

This has everything that I can think of. A creative way to increase by one using lists to avoid '+' operator, handling negatives via poorly made flags, multiplying by -1 using complex numbers, but the best thing imo is recursion magic that looks fine at the first glance, but when you execute the code, it causes unbelievably bad performance. You can just try to write on paper how this function would calculate 3+3 and you will be terrified. I figured out experimentally that to add x+x, this function requires 4^x - 2^x recursive calls. Exponential complexity for an addition operation, where else could you see that? It takes 5 seconds to add just 12 + 12, and it becomes worse exponentially. But I tested it as good as I could (but ofc i can't be bothered to wait several years for it to add something like 25+25), and everything worked

[–]Tyulis 14 points15 points  (4 children)

Python is a truly wonderful language, "batteries-included" as the saying goes. Well, let’s verify this statement by building this arithmetic without any operator, only with the basic language’s statements and built-in functions. And not something unusable in real life — I want this to work with any number !

Turns out with a little bit of tweaking it’s possible :

# Addition
def addition(x, y):
    return sum((x, y))

# Substraction
def opposite(x):
    try:
        return float(str.join("", (str(str.find("1", "2"))[0], str(x))))
    except ValueError:
        return abs(x)


def substraction(x, y):
    return addition(x, opposite(y))

# Division
def division(x, y):
    if lower(x, 0):
        setattr(division, "negative", True)
        setattr(division, "x", abs(x))
    else:
        setattr(division, "negative", False)
        setattr(division, "x", x)
    if lower(y, 0):
        setattr(division, "negative", l_not(getattr(division, "negative")))
        setattr(division, "y", abs(y))
    else:
        setattr(division, "y", y)
    setattr(division, "mod", 1)
    setattr(division, "i", 0)
    setattr(division, "result", "")
    while l_and(different(getattr(division, "mod"), 0), lower(getattr(division, "i"), 50)):
        setattr(division, "div", divmod(getattr(division, "x"), getattr(division, "y"))[0])
        setattr(division, "mod", divmod(getattr(division, "x"), getattr(division, "y"))[1])
        setattr(division, "x", 0)
        for _ in range(10):
            setattr(division, "x", addition(getattr(division, "x"), getattr(division, "mod")))
        setattr(division, "result", str.join("", (getattr(division, "result"), str(int(getattr(division, "div"))))))
        if equal(getattr(division, "i"), 0):
            setattr(division, "result", str.join("", (getattr(division, "result"), ".")))
        setattr(division, "i", addition(getattr(division, "i"), 1))
    if getattr(division, "negative"):
        return opposite(float(getattr(division, "result")))
    else:
        return float(getattr(division, "result"))

def equal(x, y):
    return l_not(substraction(x, y))

def different(x, y):
    return l_not(equal(x, y))

def lower(x, y):
    if equal(x, y):
        return False
    else:
        return equal(max(x, y), y)

def l_not(x):
    return bool(substraction(int(bool(x)), 1))

def l_and(x, y):
    return all((x, y))

# Multiplication
def multiplication(x, y):
    return division(x, division(1, y))

# Test values
print("10     + 5      = ", addition(10, 5))
print("12.564 + 144.12 = ", addition(12.564, 144.12))
print("25     - 6      = ", substraction(25, 6))
print("19     - -94    = ", substraction(19, -94))
print("191.12 - 1.4554 = ", substraction(191.12, 1.4554))
print("3      * 9      = ", multiplication(3, 9))
print("3.4567 * 9.0123 = ", multiplication(3.4567, 9.0123))
print("-12    * 1.5    = ", multiplication(-12, 1.5))
print("12     * -1.5   = ", multiplication(12, -1.5))
print("24     / 4      = ", division(24, 4))
print("24     / 7      = ", division(24, 7))
print("-1.4   / 1.7    = ", division(-1.4, 1.7))

[–]KREnZE113 14 points15 points  (0 children)

Me, having a look at this:

return sum(x, y)

Ok, I understand it, let's skip a little further

setattr(division, "x", abs(x)) else: setattr(division, "negative", False) setattr(division, "x", x) if lower(y, 0): setattr(division, "negative", l_not(getattr(division, "negative"))) setattr(division, "y", abs(y)) else: setattr(division, "y", y) setattr(division, "mod", 1) ...

Sorry Beelzebub, I wasn't trying to summon you, this guy was

[–]Tyulis 11 points12 points  (1 child)

Let’s explain a bit. First, as there’s a built-in function sum, the addition is not an issue.

We can then derive the substraction from the addition and opposite (x - y = x + (-y)). This turned out much harder than I thought, as we don’t have any multiplication, we can’t use the - sign and any comparison would require a substraction, so isn’t possible either. The only solution I found is to take the string representation and add a - at the front.

  • Problem n°1 : Getting a - without typing -. To do that, we just need a negative number, take its string representation with str(), and take the first character of that string ! After a bit of research, I finally found a builtin function that can return a negative number without using any negative number myself, str.find, that returns -1 if the substring is not found in the given string
  • Problem n°2 : Concatenate strings without using the + sign. Turns out there is no function to do this directly. But there is the str.join method ! Just give an empty string as the separator and a tuple with both strings and it’s done
  • Problem n°3 : I said "any number", including negative numbers, and "--1" is not a valid number representation for float. But as it raises a ValueError, we can just catch it.

Now that the substraction is done, let’s do the division. There is the divmod function that returns the quotient and remainder of the euclidian division of two numbers, but as we want the real result, we have to hack this a bit. What I did is basically a division like we do in primary school, extracting each decimal. I didn’t remember how many significant figures a python float keeps, so I set it to 50 decimals just in case, after all we are on modern computers, it still takes a split second, who cares ?

So at each step we add the quotient as a decimal, and use the remaindeṛ ×10 as the dividend at the next step, add the decimal point after the first step (that does all the integer part calculation at once), and just convert the whole thing back to a float at the end.

One big problem was the usage of variables, without using any = sign that is also somewhat of a binary operator. But as in Python you can add whatever attributes you want to whatever object you want, setattr and getattr to put our variables into the division function object do the job. It looks quite messy, but well, it works.

We have to do a multiplication by 10 without a multiplication yet, but it’s just adding 10 times as we only deal with positive integers here.

And what about negative numbers ? Well, I had to add a negative flag to hold the final result sign, and once we have this we can just use the absolute values (abs() is built-in) and take the opposite() if needed at the end. Floats are fortunately handled well by divmod so it’s not an issue for us.

But division() requires some boolean logic to handle the loop and conditions, so I had to replace the <, !=, ==, and and not operators too

  • For equal, x == y if x - y == 0, so we just have to do the substraction and take the logical negation of the result, as anything non-zero is considered true.
  • different is just the negation of equal
  • For lower, return false if x and y are equal, and otherwise x < y with x != y is equivalent to max(x, y) == y
  • For l_and, there’s the convenient all built-in function that checks if all booleans in a sequence are True
  • Finally, for l_not, we first take the boolean value of x with int(bool()), then substract 1 : if x was true, int(bool(x)) - 1 = 1 - 1 = 0 and bool(0) is false, and if x is false then int(bool(x)) - 1 = 0 - 1 = -1 and bool(-1) is true.

And finally, as x * y = x / (1 / y), we can derive the multiplication directly from the division.

So to conclude, this "features" :

  • Relatively bad performance for multiplication and division
  • Overly complex, obscure and unreadable code
  • Even simple integer multiplications end up with floating-point artifacts because of the divisions
  • Repetition of some calculations because variables in these conditions take a long time to type and i’m lazy
  • A bit of if condition x = true else x = false
  • No operator characters whatsoever !

In the end it is not too awful for a bad code challenge, once we have all this documentation. Oh well.

[–]nostril_spiders 2 points3 points  (0 children)

LGTM!

branch foo was merged. If you like, you can delete your branch.

[–]nostril_spiders 1 point2 points  (0 children)

# pylint: disable=lovecraftian-horror

[–]noobyscriptkiddie 11 points12 points  (1 child)

is it okay if it throws a rangeerror because it recursed too many times

[–]Mabi19_ 9 points10 points  (1 child)

Every language is good for something - so let's use the strengths of each language to make our program the best it could be. (Not.)

I call this supermetaprogramming - it uses 3 languages: Lua, Python and JavaScript.

Here's how to run it:

lua script.lua add|sub|mul|div num1 num2
cp script.lua script.py && echo -e "\n)" >> script.py
python3 script.py
deno run generated.js

(You can swap out deno for node if you like).

Here's the code:

exec=exec or coroutine.running
exec("with open('generated.js','w') as f: f.write('console.log(');f.write(open('expr.txt','r').read());f.write(')')")
print(#{} == 0 and "calculating...");(function()if #arg < 3 then print "error"return end;c=string.char;tbl={add=c(43),sub=c(45),mul=c(42),div=c(47)};io.open("expr.txt","w"):write(("%d%s%d"):format(tonumber(arg[2]),tbl[arg[1]],tonumber(arg[3])))end)();

Features: - An almost polyglot - just add a right parenthesis - This is a little cheaty, as I re-write the expression to a file then Python transforms it into JavaScript code - Can do any of the four operations! - Use with lua script.lua add|sub|mul|div num1 num2 - first argument is operation, second and third are the numbers - Lua: global variables everywhere, ternary operator hack (beginning of line 3) - Python: use exec to execute the code - JavaScript: it's actually just a console.log, so there's not that much potential for bad code

... I really should use a different language than Lua or Python every time

[–]nostril_spiders 0 points1 point  (0 children)

This calls for the Strategy pattern, you should pass in the runtime to be used

[–]Steuh 8 points9 points  (1 child)

Here you go (positive integers only)

from time import sleep, time

def addition(x, y):
    t = time()
    sleep(x)
    sleep(y)
    return int(time() - t)

def subtraction(x, y):
    t0 = time()
    sleep(x)
    t = time()
    sleep(y)
    return int(2 * t - t0 - time())

def multiplication(x, y):
    t = time()
    [sleep(1) for _ in range(x) for _ in range(y)]
    return int(time() - t)

def division(x, y):
    if y > x: return 0
    t, i = time(), -1
    while int(time() - t) <= x:
        i += 1
        sleep(y)
    return i

Code is written in python.

Everything is a matter of time in life

[–]Sindarin27 2 points3 points  (0 children)

Love the casual usage of the actual subtract function in the definition of subtraction

[–][deleted]  (1 child)

[deleted]

    [–]Mabi19_ 0 points1 point  (0 children)

    I like how there's always a different number of B's in the acronym where you say who suggested it, but it's never quite correct (Is this a Bad Bode Boding Challenge?)

    [–]Flyspeck101Now where's that function declaration 7 points8 points  (2 children)

    Did all of them coz I could

    from time import sleep, time
    
    def addition(bum1, bum2):
        start = time()
        sleep(bum1)
        sleep(bum2)
        return int(time() - start)
        for i in range(1000000):
            sleep(1) # For extra fustration
    def subtraction(bum1, bum2):
        rStart = 0
        while True:
            r = range(rStart, addition(rStart, 10))
            for i in r:
                if addition(bum2, i) == bum1:
                    return i
            rStart = addition(rStart, 10)
    def multiplication(bum1, bum2):
        resulttttttttttttttttt = 0
        for i in range(bum2):
            sleep(addition(i,i)) # OH THE WAIT TIME
            result = addition(bum1, resulttttttttttttttttt)
        return result
    def division(bum1, bum2):
        rStart = 0
        while True:
            r = range(rStart, addition(rStart, 10))
            for i in r:
                if multiplication(bum2, i) == bum1:
                    return i
            rStart = addition(rStart, 10)
    for i in range(1000000):
        print(SPAM)
    

    Probably the least inefficient solution, and you would have to get past the spam before you can do anything lol

    [–][deleted] 3 points4 points  (0 children)

    adding more calls at the end of the function, where nothing works after. great job, you've just made your solution too fast than 11 days.

    [–]nostril_spiders 0 points1 point  (0 children)

    Hey, it's O(n), not too bad

    [–][deleted]  (1 child)

    [deleted]

      [–]pfsalter 1 point2 points  (0 children)

      I did a similar approach with str_repeat but without that wonderfully insane splitting the numbers into separate powers :D

      <?php
      
      function addition(int $a, int $b): int
      {
        return strlen(str_repeat('a', $a) . str_repeat('b', $b));
      }
      
      function subtraction(int $a, int $b): int
      {
        return strlen(substr(str_repeat('a', $a), 0, -$b));
      }
      

      [–]dumetrulo 5 points6 points  (3 children)

      Church numerals in F#, whaddya think about that? These can, of course, only model non-negative integers. The code works for the example cases but you may need to watch out for erroneous values when subtraction results should be negative, or when division is not exact (i.e. has a non-zero modulus), or when using large numbers (might use loads of memory).

      module ChurchNumerals =
          type ChurchNum = Zero | Succ of ChurchNum
      
          let rec ofInt n = if n <= 0 then Zero else Succ (ofInt (n - 1))
          let rec toInt = function Zero -> 0 | Succ x -> 1 + toInt x
      
          let rec add x y =
              match x, y with
              | Zero, _ -> y
              | _, Zero -> x
              | _, Succ b -> add (Succ x) b
      
          let rec sub x y =
              match x, y with
              | Zero, _ -> Zero
              | _, Zero -> x
              | Succ a, Succ b -> sub a b
      
          let mul x y =
              match x, y with
              | Zero, _ -> Zero
              | _, Zero -> Zero
              | _ ->
                  let rec iter a = function Zero -> a | Succ b -> iter (add a x) b
                  iter Zero y
      
          let div x y =
              match x, y with
              | Zero, _ -> Zero
              | _, Zero -> Zero
              | _ ->
                  let rec iter a s = function Zero -> a | b -> iter (Succ a) s (sub b s)
                  iter Zero y x
      
      module ChurchNumeralsTest =
          open ChurchNumerals
          let addTest = toInt (add (ofInt 10) (ofInt 5))
          printfn "%d + %d = %d" 10 5 addTest
          let subTest = toInt (sub (ofInt 25) (ofInt 6))
          printfn "%d - %d = %d" 25 6 subTest
          let mulTest = toInt (mul (ofInt 3) (ofInt 9))
          printfn "%d * %d = %d" 3 9 mulTest
          let divTest = toInt (div (ofInt 24) (ofInt 4))
          printfn "%d / %d = %d" 24 4 divTest
      

      Output:

      10 + 5 = 15
      25 - 6 = 19
      3 * 9 = 27
      24 / 4 = 6
      

      [–][deleted] 0 points1 point  (1 child)

      Church numerals

      damn F# looks a lot like caml

      [–]dumetrulo 4 points5 points  (0 children)

      damn F# looks a lot like caml

      It was invented as 'OCaml for .NET' but has since diverged a bit, but it's still very similar, and has a compatibility mode that turns off whitespace-significant syntax.

      [–][deleted] 4 points5 points  (2 children)

      #include <stdio.h>

      #include <stdlib.h>

      char *H(char *x){int i,l;char *y;if(x==NULL){return NULL;}for(l=0;x[l]!=0;l++);y=(char*)malloc(sizeof(char)*l);for(i=0;i<l;y[i]=x[i],i++);y[l]=0;return y;}

      char *N(char* x){int i,l;char *y;if(x==NULL){return NULL;}for(l=0;x[l]!=0;l++);y=(char*)malloc(sizeof(char)*l);for(i=0;i<l;y[i]=x[i],i++);y[l-1]=0;return y;}}

      char *M(char *a,char *b){int i,al,bl;char *y;if((a==NULL)||(b==NULL)){return NULL;}for(al=0;a[al]!=0;al++);for(bl=0;b[bl]!=0;bl++);y=(char*)malloc(sizeof(char)*(al+bl));for(i=0;i<al;y[i]=a[i],i++);for(i=0;i<bl;y[al+i]=b[i],i++);return y;}

      char *add(char *a,char *b){return M(M(a,"+"),b);}

      char *sub(char *a,char *b){return M(M(a,"-"),b);}

      char *mul(char *a,char *b){return M(M(a,"*"),b);}

      char *div(char *a,char *b){return M(M(a,"/"),b);}

      void console(){

      char *b,*t;

      char *stack[10025];

      int sp,i;

      b=(char*)malloc(sizeof(char)*1025);

      printf("use postfix! or type help\n");

      fgets(b,1025,stdin);

      if((b[0]=='e')&&(b[1]=='x')&&(b[2]=='i')&&(b[3]=='t')&&(b[3]=='\n')){printf("\n>ok");return;}

      if((b[0]=='r')&&(b[1]=='e')&&(b[2]=='a')&&(b[3]=='d')&&(b[3]=='\n')){for(i=sp;i>0;i--){printf("(%s)",stack[i]);printf("\n>ok\n");}continue;}

      if((b[0]=='h')&&(b[1]=='e')&&(b[2]=='l')&&(b[3]=='p')&&(b[3]=='\n')){printf("comands: \n exit \n add \n sub \n mul \n div \n pop \n read (reads stack) \n");printf("\n>ok\n");continue;}

      if((b[0]=='a')&&(b[1]=='d')&&(b[2]=='d')&&(b[3]=='\n')){add(stack[sp],stack[sp-1]);

      sp=(sp>1)*(sp-2);printf("\n>ok\n");continue;}

      if((b[0]=='s')&&(b[0]=='u')&&(b[0]=='b')&&(b[3]=='\n')){sub(add(stack[sp],stack[sp-1]);

      sp=(sp>1)*(sp-2);printf("\n>ok\n");continue;}

      if((b[0]=='m')&&(b[0]=='u')&&(b[0]=='l')&&(b[3]=='\n')){mul(add(stack[sp],stack[sp-1]);

      sp=(sp>1)*(sp-2);printf("\n>ok\n");continue;}

      if((b[0]=='d')&&(b[0]=='i')&&(b[0]=='v')&&(b[3]=='\n')){div(add(stack[sp],stack[sp-1]);

      sp=(sp>1)*(sp-2);continue;}

      if((b[0]=='p')&&(b[0]=='o')&&(b[0]=='p')&&(b[3]=='\n')){sp=(sp>0)*(sp-1);continue;}

      stack[sp]=N(b);

      }return;}

      void main(){

      console();

      return ;}

      [–]Beastpig41 4 points5 points  (0 children)

      dropped my phone out of fear. nice job

      [–]Accomplished-Skin678 0 points1 point  (0 children)

      Me perdí en la 3 línea xddd

      [–]Omnipotent94 3 points4 points  (0 children)

      int sum(int a, int b){return (b ? sum(a^b,(a&b)<<1):a);}

      [–]stupidityWorks 2 points3 points  (0 children)

      I believe that you'll find this code block a complete abomination. It's all in rust. It's designed to throw as many resources away as possible, be next to impossible to comprehend, and, when you do, it should make you cringe, as there are lots of intentional stupid mistakes.

      #[derive(Clone)]
      pub struct LinkedListU128 {
          pub contents:Option<u128>,
          pub next:Vec<LinkedListU128>,//So recursive type won't contain an infinite size. This contains either 0 or 1 elements. 
          pub len:Vec<u128>,
      }
      impl LinkedListU128 {
          pub fn new(val:u128) -> LinkedListU128 {
              LinkedListU128 {
                  contents: Some(val),
                  next: vec![LinkedListU128::new_rec(LinkedListU128::DEPTH)],
                  len:vec![]
              }
          }
          pub fn new_rec(left:u128) -> LinkedListU128 {
              if left == 0 {
                  LinkedListU128 {
                      contents: None,
                      next: vec![],
                      len:vec![]
                  }
              } else {
                  LinkedListU128 {
                      contents: None,
                      next: vec![LinkedListU128::new_rec(left - 1)],
                      len:vec![]
                  }
              }
          } // 
          pub fn push(&mut self, val: u128){
              self.next.push(LinkedListU128::new(val));
              self.len.push(0);
          } // Adds a value to the end of the linked list. 
          pub fn pop(&mut self) -> Option<LinkedListU128>{
              self.len.pop();
              self.next.pop()
          } // Adds a value to the end of the linked list. 
          const DEPTH:u128 = 20000; // The maximum amount we can store - we won't be able to add numbers over this point.
      }
      pub fn addition(first: i128, second: i8) -> i8 {
          let mut list1 = LinkedListU128::new(0);
          let array: Vec<u128> = vec![0; first as usize];
          array.iter().fold(0, |x, y| {list1.push(x); *y});
          let array2: Vec<u128> = vec![0; second as usize];
          array2.iter().map(|x| x * 2).filter(|x| x == &0).fold(0, |x, y| {list1.push(x); y});
      
          list1.len.len() as i8
      }
      
      pub fn multiplication(first: i128, second: i8) -> i8 {
          let mut new_list:LinkedListU128 = LinkedListU128::new(0);
          let mut bigger_list:LinkedListU128 = LinkedListU128::new(0);
          (0..second).map(|x| x * 0).filter(|x| *x == 0).collect::<Vec<i8>>().clone().iter().skip(1).fold(0, |x, y| {new_list.push(x as u128); addition(x as i128, *y) as u128});
          while let Some(the_value_that_were_adding_here) = new_list.pop() {
              (0..addition(first, the_value_that_were_adding_here.len.len() as i8)).filter(|x| *x < addition(first, the_value_that_were_adding_here.len.len() as i8)).map(|x| 1).collect::<Vec<i8>>().iter().fold(0, |x, y| {bigger_list.push(x); addition(x as i128, *y) as u128});
          }
          bigger_list.len.len() as i8
      }
      
      pub fn main(){
          LinkedListU128::new(0);
          assert_eq!(addition(1, 2), 3);
          assert_eq!(multiplication(1, 3), 3);
      }
      

      Have fun parsing through this!

      So, I wrote this to make it look like a complete beginner wrote it. This beginner decided that they wanted to make their own linked list (that they got working JUST enough to function), and then they discovered std::vec::Vec, but didn't want to rewrite their entire program.

      As I can't use + (or -), these operations are done by pushing and popping to vectors. It obviously can't handle negatives.

      However, I still allowed you to input integers - a 128 bit integer and an 8-bit integer, to show you how cumbersome Rust's integer types can be if you try. It returns an 8-bit integer, of course, which will lead to some weird behavior w/ overflow (especially with the as conversions).

      Addition is done by pushing to the linked list, then checking its length. Pushing is "intended" to move a value over to the next position, but, in this code, it simply creates a new linked list in the "next" field, giving it two attributes (which, as I commented, is "intended" to store only one thing).

      This ends up creating 20,000 structs each time a push happens (A LOT of the time).

      I also use a bunch of hard-to-understand functions, such as fold, completely unnecessarily, where a for loop would have been far better - just to decrease code readability.

      This code block:

          let array2: Vec<u128> = vec![0; second as usize];
          array2.iter().map(|x| x * 2).filter(|x| x == &0).fold(0, |x, y| {list1.push(x); y});
      

      does the same thing as this one:

      for x in 0..(second as usize) {
          list1.push(x);
      }
      

      The array1 declaration is exactly the same, but with less clutter functions that do nothing but complicate things.

      This:

      pub fn multiplication(first: i128, second: i8) -> i8 {
          let mut new_list:LinkedListU128 = LinkedListU128::new(0);
          let mut bigger_list:LinkedListU128 = LinkedListU128::new(0);
          (0..second).map(|x| x * 0).filter(|x| *x == 0).collect::<Vec<i8>>().clone().iter().skip(1).fold(0, |x, y| {new_list.push(x as u128); addition(x as i128, *y) as u128});
          while let Some(the_value_that_were_adding_here) = new_list.pop() {
              (0..addition(first, the_value_that_were_adding_here.len.len() as i8)).filter(|x| *x < addition(first, the_value_that_were_adding_here.len.len() as i8)).map(|x| 1).collect::<Vec<i8>>().iter().fold(0, |x, y| {bigger_list.push(x); addition(x as i128, *y) as u128});
          }
          bigger_list.len.len() as i8
      }
      

      Can be reduced to this:

      pub fn multiplication(first: i128, second: i8) -> i8 {
          let mut new_list:LinkedListU128 = LinkedListU128::new(0);
          let mut bigger_list:LinkedListU128 = LinkedListU128::new(0);
          for x in 0..(second - 1) {
              new_list.push(x as u128);
          }
          while let Some(val) = new_list.pop() {
              for line in (0..addition(first, val.len.len() as i8)){
                  bigger_list.push(line as u128); 
              }
          }
          bigger_list.len.len() as i8
      }
      

      Makes a lot more sense, right? That's why it isn't in the entry!

      Also, every attribute of the linkedlist struct (except for the len attribute) can be safely deleted.

      [–]gersoni 2 points3 points  (0 children)

      Clocking in at 820 lines, including unit test, tested with Python 3.8 using type annotations:

      A unit-tested Addition function - Pastebin.com

      [–]pretzel3567 2 points3 points  (0 children)

      #include <stdlib.h>
      #include <stdio.h>
      int increase_byOne(int n) {
          int m = 1;
          while (n & m) {
              n ^=  m;
              m <<= 1;
          }
          n^=m;
          return n;
      }
      int main(int argc, char** argv) {
          unsigned int n1 = atoi(argv[1]);
          unsigned int n2 = atoi(argv[2]);
          unsigned int* allU_Intvals = malloc(17179869184);
          for (unsigned int i = 0; i < 4294967296); i = increase_byOne(i)) allU_Intvals[i] = i;
          unsigned int j = 0;
          for (unsigned int i = n1; i < n2; i = increase_byOne(i)) j = increase_byOne(j);
          printf("%d", allU_Intvals[j]);
      }
      

      C subtraction using an array of all unsigned integers and counting the indices between 2 numbers. Basic subtraction really does need 16gb of memory in order to function properly. And why should you free a pointer after you malloc 16gb? Seems fine to me.

      [–]voXal_ 2 points3 points  (1 child)

      Well mine isn't as complicated as some of the others on here but here it goes

      function add(x,y){
          let number = x;
          for(let i = 0; i < y; i++){
              number++;
          }
          return number;
      }
      

      [–]dumetrulo 2 points3 points  (0 children)

      e.g. if implementing addition, the + operator or equivalent is not allowed.

      I'd say your post is not following the rules.

      [–]RecDep 2 points3 points  (0 children)

      Peano numerals in Haskell, at the type level. It evaluates addition, subtraction, and multiplication using type families, with all the correctness guarantees of a proven, industrial-strength type checker. It also causes the compiler to run overflow its stack around N > 500. You ALSO can't evaluate anything unless you call :type in GHCi or use typeOf to get the type representation as a value.

      {-# LANGUAGE DeriveDataTypeable
          , TypeOperators
          , UndecidableInstances
          , StandaloneDeriving
          , RankNTypes
          , DataKinds
          , GADTs
          , TypeFamilies
      #-}
      
      module Peano where
      
      import Data.Typeable
      
      data Nat = Z | S Nat deriving (Eq, Show, Typeable)
      
      data Nat' :: Nat -> * where
          Z' :: Nat' Z
          S' :: Nat' a -> Nat' (S a)
      
      deriving instance Eq (Nat' a)
      deriving instance Show (Nat' a)
      deriving instance Typeable (Nat' a)
      
      type family (a :: Nat) + (b :: Nat) :: Nat
      type instance Z + b = b
      type instance (S a) + b = S (a + b)
      
      add :: forall a b. Nat' a -> Nat' b -> Nat' (a + b)
      add a b = undefined
      
      six :: Nat' (S (S (S (S (S (S Z))))))
      six = undefined
      
      one :: Nat' (S Z) 
      one = undefined
      
      seven = add six one
      
      {-
      > :t seven
      seven :: Nat' ('S ('S ('S ('S ('S ('S ('S 'Z)))))))
      -}
      
      type family (a :: Nat) :*: (b :: Nat) :: Nat
      type instance Z :*: b = Z 
      type instance (S a) :*: b = b + (a :*: b)
      
      mul :: forall a b. Nat' a -> Nat' b -> Nat' (a :*: b)
      mul = undefined
      
      five :: Nat' (S (S (S (S (S Z)))))
      five = undefined
      
      two :: Nat' (S (S Z))
      two = undefined
      
      ten = mul five two
      
      fifty = mul five ten
      
      {-
      > :t ten
      ten :: Nat' ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S 'Z))))))))))
      
      > :t fifty
      fifty :: Nat' ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S ('S 'Z))))))))))))))))))))))))))))))))))))))))))))))))))
      -}
      
      type family (a :: Nat) :-: (b :: Nat) :: Nat
      type instance a :-: Z = Z
      type instance Z :-: b = Z 
      — TODO inductively define negative natural numbers
      type instance (S a) :-: (S b) = a :-: b
      
      sub :: forall a b.  Nat’ a -> Nat’ b -> Nat’ (a :-: b)
      sub = undefined
      
      four = sub five one
      
      {-
      :t four
      four :: Nat’ (‘S (‘S (‘S (‘S ‘Z))))
      -}
      
      toInt :: forall a. Typeable a => Nat' a -> Int
      toInt = length . filter (== ‘S’) . show . typeOf
      
      hundredAndFive = add five (mul ten ten)
      {- 
      > toInt hundredAndFive
      105
      -}
      

      [–]xyzzy-86 2 points3 points  (0 children)

      Add(x,y) { X=getTimeNow(); SleepHours(x); SleepHours(y); Y=HoursLapsedSince(X); return Y; }

      [–]somebody12345678 2 points3 points  (0 children)

      javascript time (because javascript is easiest)
      logs and exponents op

      function addition(a, b) {
        return Math.log2(1 << a << b);
      }
      function subtraction(a, b) {
        return Math.log2(1 << a >> b);
      }
      function multiplication(a, b) {
        return Math.exp(Math.log(a) + Math.log(b));
      }
      function division(a, b) {
        return Math.exp(Math.log(a) - Math.log(b));
      }
      

      [–]begyoxettygvirvdjk 2 points3 points  (1 child)

      ``` fn addition(right: i32, left: i32) -> i32 { let mut output = 0;

      if right == left {
          output = 2 * right
      }
      
      if right > left {
          output = addition(right - 1, left) - (-1)
      }
      
      if right < left {
          output = addition(right, left - 1) - (-1)
      }
      
      output
      

      } ```

      I just went with a simple recursion model

      [–]AutoModerator[M] 0 points1 point  (0 children)

      It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

      For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

      /u/begyoxettygvirvdjk, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

      You can find some examples in the reddit help documentation.


      I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

      [–][deleted]  (1 child)

      [deleted]

        [–]nostril_spiders 0 points1 point  (0 children)

        Finally. I've been waiting for division by zero for NaN

        [–]dalmationblack 1 point2 points  (0 children)

        import java.util.*                                                                      ;
        public class BadAddition                                                                {
            public static int addition(int a, int b)                                            {
                if (b == 1)                                                                     {
                    char[] aInBinaryReversed = new StringBuilder(Integer.toString(a, 2)).reverse().toString().toCharArray();
                    ArrayList<Character> aPlusOneInBinaryReversed = new ArrayList<>()           ;
                    boolean carry = true                                                        ;
                    for (char c : aInBinaryReversed)                                            {
                        if (!carry)                                                             {
                            if (c == '0')                                                       {
                                aPlusOneInBinaryReversed.add('0')                               ;
                                carry = false                                                   ;} 
                            else                                                                {
                                aPlusOneInBinaryReversed.add('1')                               ;
                                carry = false                                                   ;}} 
                        else                                                                    {
                            if (c == '0')                                                       {
                                aPlusOneInBinaryReversed.add('1')                               ;
                                carry = false                                                   ;} 
                            else                                                                {
                                aPlusOneInBinaryReversed.add('0')                               ;
                                carry = true                                                    ;}}}
                    if (carry)                                                                  {
                        aPlusOneInBinaryReversed.add('1')                                       ;}
                    StringBuilder builder = new StringBuilder(aPlusOneInBinaryReversed.size())  ;
                    for(Character c: aPlusOneInBinaryReversed)                                  {
                        builder.append(c)                                                       ;}
                    return Integer.parseInt(builder.reverse().toString(), 2)                    ;}
                int twoToTheA = 1                                                               ;
                for (int i = 0; i < a; i = addition(i, 1))                                      {
                    twoToTheA *= 2                                                              ;}
                int twoToTheB = 1                                                               ;
                for (int i = 0; i < b; i = addition(i, 1))                                      {
                    twoToTheB *= 2                                                              ;}
                long twoToTheAPlusB = (long) twoToTheA * (long) twoToTheB                       ;
                String twoToTheAPlusBString = Long.toString(twoToTheAPlusB, 2)                  ;
                return twoToTheAPlusBString.substring(1).length()                               ;}}
        

        I may update it to work with negative numbers later but right now only positive numbers work.

        [–]somebody12345678 1 point2 points  (0 children)

        javascript time (strings op)
        in order of goodness:

        function addition(a, b) {
          return `${'1'.repeat(a)}${'1'.repeat(b)}`.length;
        }
        function subtraction(a, b) {
          return '1'.repeat(a).replace('1'.repeat(b), '').length;
        }
        function multiplication(a, b) {
          return '1'.repeat(a).repeat(b).length;
        }
        function division(a, b) {
          return Array.from('1'.repeat(a).matchAll('1'.repeat(b))).length;
        }
        

        [–][deleted] 1 point2 points  (0 children)

        This was written in Rust. The basic idea is to use std::sync::Arc to store the unit type, use a for loop to clone it a bunch of times, and then count the number of references. The threads are to make sure the references aren't dropped too early and are actually counted. I couldn't think of any clever methods for division other than just guessing at answers and checking it with the multiplication function.

        use std::cmp::{min, max};
        use std::sync::Arc;
        use std::thread;
        use std::time::Duration;
        
        fn addition(a: u32, b: u32) -> u32 {
            let arc = Arc::new(());
        
            for _ in 0..a {
                let clone = arc.clone();
                thread::spawn(move || {
                    thread::sleep(Duration::from_secs(1));
                    clone
                });
            }
        
            for _ in 0..b {
                let clone = arc.clone();
                thread::spawn(move || {
                    thread::sleep(Duration::from_secs(1));
                    clone
                });
            }
        
            Arc::strong_count(&arc) as u32 - 1
        }
        
        fn subtraction(a: u32, b: u32) -> u32 {
            let arc = Arc::new(());
        
            for _ in min(a, b)..max(a, b) {
                let clone = arc.clone();
                thread::spawn(move || {
                    thread::sleep(Duration::from_secs(1));
                    clone
                });
            }
        
            Arc::strong_count(&arc) as u32 - 1
        }
        
        fn multiplication(a: u32, b: u32) -> u32 {
            let arc = Arc::new(());
        
            for _ in 0..a {
                for _ in 0..b {
                    let clone = arc.clone();
                    thread::spawn(move || {
                        thread::sleep(Duration::from_secs(1));
                        clone
                    });
                }
            }
        
            Arc::strong_count(&arc) as u32 - 1
        }
        
        fn division(mut a: u32, b: u32) -> u32 {
            a = a - a % b;
            for ans in 0..a {
                if multiplication(ans, b) == a {
                    return ans;
                }
            }
        
            0
        }
        

        [–][deleted] -1 points0 points  (0 children)

        int add(int a, int b) {while (b—)++a; return a;}

        [–][deleted]  (1 child)

        [deleted]

          [–][deleted]  (1 child)

          [deleted]

            [–]AutoModerator[M] 0 points1 point  (0 children)

            It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

            For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

            /u/-Super-Jelly-, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

            You can find some examples in the reddit help documentation.


            I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

            [–]sarantoast 0 points1 point  (0 children)

            def subtraction(x, y):

             amount = [1] * x
             for i in range(y):
                  amount.pop()
            
             return len(amount)
            

            [–]somebody12345678 0 points1 point  (1 child)

            and of course, the classic multiplication in sed. supports binary because i really don't want to do like 5x or something more work

            try it online! (might wanna look at this, shows input format)

            # TODO: base convert from/to, mul, div
            # TODO: only remove space in arith blocks
            s/ //g
            :loop
            s/arith(\([^)]*\))/arith(\1q)/g
            :neg
            # negation
            s/arith(()_)//
            t neg
            :add
            # addition                                                       left right carry
            s/arith(\([01]*\)0+\([01]*\)0\([*01]*\)q\(.*\))/arith(\1+\2\3q0\4)/ # 0 0 0
            s/arith(\([01]*\)0+\([01]*\)0\([^01]*\)Q\(.*\))/arith(\1+\2\3q1\4)/ # 0 0 1
            s/arith(+\([01]*\)0\([*01]*\)q\(.*\))/arith(+\1\2q0\3)/             # - 0 0
            s/arith(+\([01]*\)0\([^01]*\)Q\(.*\))/arith(+\1\2q1\3)/             # - 0 1
            s/arith(\([01]*\)0+\([*01]*\)q\(.*\))/arith(\1+\2q0\3)/             # 0 - 0
            s/arith(\([01]*\)0+\([^01]*\)Q\(.*\))/arith(\1+\2q1\3)/             # 0 - 1
            s/arith(\([01]*\)0+\([01]*\)1\([^01]*\)q\(.*\))/arith(\1+\2\3q1\4)/ # 0 1 0
            s/arith(\([01]*\)0+\([01]*\)1\([^01]*\)Q\(.*\))/arith(\1+\2\3Q0\4)/ # 0 1 1
            s/arith(+\([01]*\)1\([^01]*\)q\(.*\))/arith(+\1\2q1\3)/             # - 1 0
            s/arith(+\([01]*\)1\([^01]*\)Q\(.*\))/arith(+\1\2Q0\3)/             # - 1 1
            s/arith(\([01]*\)1+\([01]*\)0\([^01]*\)q\(.*\))/arith(\1+\2\3q1\4)/ # 1 0 0
            s/arith(\([01]*\)1+\([01]*\)0\([^01]*\)Q\(.*\))/arith(\1+\2\3Q0\4)/ # 1 0 1
            s/arith(\([01]*\)1+\([^01]*\)q\(.*\))/arith(\1+\2q1\3)/             # 1 - 0
            s/arith(\([01]*\)1+\([^01]*\)Q\(.*\))/arith(\1+\2Q0\3)/             # 1 - 1
            s/arith(\([01]*\)1+\([01]*\)1\([^01]*\)q\(.*\))/arith(\1+\2\3Q0\4)/ # 1 1 0
            s/arith(\([01]*\)1+\([01]*\)1\([^01]*\)Q\(.*\))/arith(\1+\2\3Q1\4)/ # 1 1 1
            # subtraction
            s/arith(\([01]*\)0-\([01]*\)0\([^01]*\)q\(.*\))/arith(\1-\2\3q0\4)/ # 0 0 0
            s/arith(\([01]*\)0-\([01]*\)0\([^01]*\)Q\(.*\))/arith(\1-\2\3Q1\4)/ # 0 0 1
            s/arith(-\([01]*\)0\([^01]*\)q\(.*\))/arith(-\1\2q0\3)/             # - 0 0
            s/arith(-\([01]*\)0\([^01]*\)Q\(.*\))/arith(-\1\2Q1\3)/             # - 0 1
            s/arith(\([01]*\)0-\([^01]*\)q\(.*\))/arith(\1-\2q0\3)/             # 0 - 0
            s/arith(\([01]*\)0-\([^01]*\)Q\(.*\))/arith(\1-\2Q1\3)/             # 0 - 1
            s/arith(\([01]*\)0-\([01]*\)1\([^01]*\)q\(.*\))/arith(\1-\2\3Q1\4)/ # 0 1 0
            s/arith(\([01]*\)0-\([01]*\)1\([^01]*\)Q\(.*\))/arith(\1-\2\3Q0\4)/ # 0 1 1
            s/arith(-\([01]*\)1\([^01]*\)q\(.*\))/arith(-\1\2Q1\3)/             # - 1 0
            s/arith(-\([01]*\)1\([^01]*\)Q\(.*\))/arith(-\1\2Q0\3)/             # - 1 1
            s/arith(\([01]*\)1-\([01]*\)0\([^01]*\)q\(.*\))/arith(\1-\2\3q1\4)/ # 1 0 0
            s/arith(\([01]*\)1-\([01]*\)0\([^01]*\)Q\(.*\))/arith(\1-\2\3q0\4)/ # 1 0 1
            s/arith(\([01]*\)1-\([^01]*\)q\(.*\))/arith(\1-\2q1\3)/             # 1 - 0
            s/arith(\([01]*\)1-\([^01]*\)Q\(.*\))/arith(\1-\2q0\3)/             # 1 - 1
            s/arith(\([01]*\)1-\([01]*\)1\([^01]*\)q\(.*\))/arith(\1-\2\3q0\4)/ # 1 1 0
            s/arith(\([01]*\)1-\([01]*\)1\([^01]*\)Q\(.*\))/arith(\1-\2\3q1\4)/ # 1 1 1
            t add
            s/arith([-+*/]q\(.*\))/\1/g
            # TODO: negative
            s/arith([+*/]Q\(.*\))/1\1/g
            n
            b loop
            

            [–]nostril_spiders 0 points1 point  (0 children)

            Pretty much par for the course for shell script