A while back, when I was a student in Paris, one of our teachers told us about some project from University of Valladolid (I can’t remember the actual name of the project), it was a contest for programmers, and the goal was to solve as many simple algorithmic problems as possible.
At that time, I thought it was pretty cool, since most of the class was only beginning to understand programming (the class was something like C programming 101), so I used to look at problems and solved them.
I was thinking about that a couple of weeks ago, and I found out that the project still exists, it only changed location/name, which means that I lost my account data (it’s not that bad), but which also means I can keep having fun with it!
You know, by having fun, I mean actually having to think of algorithms and write them myself, you can read this article if you’re not sure what I mean.
Anyway, long story short, the project is UVa Online Judge and it’s awesome!
As a bonus, here’s my solution for the first problem: The 3n + 1 problem
Have fun!
// Q100 - The 3n + 1 problem
// http://bit.ly/2aRM6Y
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#define MAXNUMBER 1000000
unsigned int cycleLength (unsigned int *known, unsigned int i)
{
unsigned int length;
if (i == 1)
length = 1;
else if (i < MAXNUMBER && known[i] != 0)
length = known[i];
else if (i % 2)
{
length = 1 + cycleLength (known, i * 3 + 1);
if (i < MAXNUMBER)
known[i] = length;
}
else
{
length = 1 + cycleLength (known, i / 2);
if (i < MAXNUMBER)
known[i] = length;
}
return length;
}
int main (int argc, char **argv)
{
unsigned int *knownCycles;
unsigned int max, len, a, b, i, start, end;
knownCycles = calloc (MAXNUMBER, sizeof (unsigned int));
while (scanf ("%u %u", &a, &b) != EOF)
{
max = 0;
start = (a > b) ? b : a;
end = (a > b) ? a : b;
for (i = start; i <= end; i++)
{
len = cycleLength (knownCycles, i);
if (len > max)
max = len;
}
printf ("%u %u %u\n", a, b, max);
}
free (knownCycles);
return 0;
}
Subscribe
Leave a Reply