Tinker, Tailor, Soldier, Sponge

View Original

Project Euler

Euler and his famous equation

In which I get back into coding in C...

I did a programming course* during my undergrad but it's fallen by the wayside recently. In an effort to improve my coding skills, and my understanding of maths, I have started on Project Euler.

*I took two actually but only had time for the coursework in one - I might upload my program for it later.

Project Euler

Project Euler (http://projecteuler.net/) is a website which sets maths problems and asks you to solve them with programming. There are currently 410 problems for you to solve.

They usually give an example or two and then ask for a harder calculation. Par example, the 6th prime number is 13 - now find the 15,000th.

This has been very helpful for re-learning my coding skills. You have to break down the maths problem into steps and then work out how the hell you would code that. Also it's fun and challenging!

Timing

Project Euler says every problem on the site is solvable in about 1 minute. In order to keep track of how good my programs are I've been using a simple timing system that works on Linux. You will need to call stdio.h, time.h and unistd.h:

int main()
{
int p = (int) getpid();
clock_t cstart = clock();
clock_t cend = 0;

// Rest of Program

cend = clock();
printf("%.3f cpu secn", ((double)cend - (double)cstart)* 1.0e-6);
return 0;
}


Code Monkey - not Maths Monkey!

"Rob say Code Monkey very diligent, But his output stink, His code not 'functional' or 'elegant', What do Code Monkey think?"

My code definitely isn't elegant but it is working. I'm definitely using a brute force approach at the moment. I've just rushed through 3 problems in a row with very little need for an understanding of more than basic maths. A few nested loops and I was away. Sadly I'm now on the aforementioned prime number program and it is taking aaages to run.

This however is the cool thing about Project Euler - in order to solve these problems my programming knowledge† isn't enough. I need to research the maths behind it. As a Physicist I see maths as a tool normally - now I can start to appreciate the elegance of it, which is cool :)

And once I've learnt about the maths behind the problem I need to change my code. This makes me learn new coding techniques and improve my programming skill - win, win!

†and, err, lack of skill.

Tom Out!

P.S. My Prime number program started running before I started this post and is still going - I think I need to re-write it :/