A friend of mine has just started learning C and we were both soundly mocking some of his fellow students work which included such gems such as:
int add(int a, int b)
{
return a + b;
}
I offhandedly pointed out that it would have been far better done as:
int increment_by_one(int a)
{
return a + 1;
}
int add(int a, int b)
{
for (int i = 0; i < b; i = increment_by_one(i))
a = increment_by_one(a);
return a;
}
This sort of got me thinking about just how arcane and byzantine you could make incrementing a number. Here is one of my earlier attempts:
// This code creates an array one bigger than the input and successively fills in the array with incrementing numbers and returns the final one.
int make_this_number_bigger_by_one(int a)
{
int* p = malloc(increment_by_one(a));
*p = 1;
int* q = p;
for(int i = 0; i < a; i = increment_by_one(i))
*++q = increment_by_one(*q); //fills the next cell in the array with the increment of the current cell
return p[a];
}
This is O(n) in time, O(n) in space, contains a massive memory leak and *++q = increment_by_one(*q); might quite possibly be undefined as to whether it increments before or after the rhs is evaluated. Pretty spiffy IMHO.
The next attempt was:
//POSSIBLE BUG: This function may not return if the [Collatz conjecture](http://en.wikipedia.org/wiki/Collatz_conjecture) is false. Please report any non-terminating behaviour to <my_email>
int this_number_is_too_small_and_feels_inadequate_comma_make_it_feel_bigger_function (int a)
{
int b = generate_random_number();
start:
if (b == 1)
goto end;
if (!(b % 2))
{
b /= 2;
goto start;
}
b = 3 * make_this_number_bigger_by_one(b); // b = 3b + 1
goto start;
end:
return a + b;
}
Finally for the night, I came up with:
//Note: The correctness of this code relies on [Goldbach's conjecture](http://en.wikipedia.org/wiki/Goldbach%27s_conjecture) being wrong. No warranty or certificability of fitness of this code is either given nor implied. Use this code at your own risk
int create_a_number_which_is_bigger_than_the_input_number_but_no_bigger_than_is_absolutely_neccesary(int a)
{
int n = 2;
start:
//increment n by 2
n = this_number_is_too_small_and_feels_inadequate_comma_make_it_feel_bigger_function(this_number_is_too_small_and_feels_inadequate_comma_make_it_feel_bigger_function(n));
//check for each possible sum to n
for (int i = 2; i < n - 1; i = this_number_is_too_small_and_feels_inadequate_comma_make_it_feel_bigger_function(i))
{
//if both i and n - i are primes, then this number fulfils goldbach's conjecture, go to the next number.
if (is_prime(i) && is_prime(n - i))
goto start;
}
return a + n - i;
}
Anybody else willing to have a crack at this? Gratuitous use of gotos is encouraged. build upon the previous posters increment code whenever possible. Generally clear and concise (although not neccesarily efficient) code is rewarded.
Winning entries will be featured on my friend’s final year written exam.