I was doing some practice problems earlier today, one of them was implementing addition using only bit operators. After that I implemented addition that only uses increment/decrement operators, just for fun:
int dumb_addition(int a, int b) {
int temp_a = a, temp_b = b, sum = 0;
while (temp_a > 0) {
sum++;
temp_a--;
}
while (temp_b > 0) {
sum++;
temp_b--;
}
return sum;
}
Nevermind the useless temp variables or the fact that this won't work for negative numbers.
Here's some code I ran comparing dumb_addition with my bit_addition function, just to illustrate how terrible my dumb_addition function was:
static void Main() {
string s = "Elapsed ticks for {0} is: {1}";
var stopwatch = new Stopwatch();
stopwatch.Start();
int x = bit_addition(int.MaxValue, int.MaxValue);
stopwatch.Stop();
Console.WriteLine(String.Format(s, "bit_addition", stopwatch.ElapsedTicks));
stopwatch.Reset();
stopwatch.Start();
x = dumb_addition(int.MaxValue, int.MaxValue);
stopwatch.Stop();
Console.WriteLine(String.Format(s, "dumb_addition", stopwatch.ElapsedTicks));
}
With the output:
Elapsed ticks for bit_addition is: 769
Elapsed ticks for dumb_addition is: 31337684
Elapsed ticks for dumb_addition is: 31337684
Brute force isn't always the answer, kids :(
Speaking of code that makes you laugh, I remember seeing some kid's program where he commented EVERY single line of code. Most amusing was the fact that he commented the statement "return x" with "//return x". I had a chuckle over that one after shaking my head disapprovingly.