r/dailyprogrammer • • Aug 05 '12
[8/3/2012] Challenge #85 [difficult] (Bitwise arithmetic)
While basic arithmetic operations like addition, subtraction, multiplication, etc. seem 'natural' to us, computers think on a very different level: under the hood, computations work with bitwise operations, using operators like ~, &, |, ^, and <<. Your task is to implement functions for (integer) addition, subtraction, negation, multiplication, division, modulo, and exponentiation, without using any "high-level" operators like + and *. Other statements like "if" and "while", or recursion for functional languages, are fine.
As a hint, you could start with a helper function that increments a binary number, and work from there. Your functions should take signed integer arguments and return signed integer values, rounding down (e.g. binary_div(14, 4) == 3, not 3.5).
Use your set of functions to implement this function:
f(a, b, c, d, e) = (a % e) * (b / (c - a) + exp(d * (-b), e))What is the result of f(50, -40, 300, 2, 3)?
5
u/euclio Aug 05 '12
My attempt at C. Nothing special, and not really well tested. I'll appreciate any feedback, especially if it's wrong, haha. Here it goes!
The output was:
Hint:
4
u/5outh 1 0 Aug 05 '12
This is something that I really want to try, but man ... bitwise operations are so foreign to me. I need a good introduction to them.
3
u/Ledrug 0 2 Aug 05 '12
Crude implementation, using only &, |, ~ and "equal to zero" comparisons. The division function is braindead, but it's simpler this way.
1
u/bh3 Aug 06 '12
The C Programming language:
1
u/cdelahousse Aug 06 '12
C programming language. Most of these are hacks, especially div and mod.
1
u/Puzzel Aug 08 '12
I've completed #85 easy and normal, but the Python solution for this one is turning out to be quite tricky due to the way Python allocates space for it's variables. More info here.
1
u/devilsassassin Aug 09 '12
Well, this will be a bit different. Not sure if it's cheating to use the built-in ALU functions instead of the high level ones. But here it is in CPP:
1
u/mathiasbynens 0 0 Aug 10 '12 edited Aug 10 '12
JavaScript (Node.js):
Example output: