Wednesday, February 23, 2011

Project Euler 3



http://projecteuler.net/index.php?section=problems&id=3

I solved this one, but I'm not happy about it because I somewhat cheated. I remember from somewhere that when testing for primes (or I suppose any multiple?) you only need to test from 1 to the square root of the number in question. I was able to implement this and the program ran a bit over two minutes before finding the answer. Before I was testing all the way up to the number and the program was taking forever and I got impatient.

Anyways, I call it cheating because I don't understand why it works out like that. Why am I allowed to only test up to the square root of the number in question? Further study is needed.

A few more things about this program I'm not happy about:

1) I'm using "unsigned long int" because I didn't want to worry about my test number being to large for int or long int. I am being lazy (hard to do things fast on the netbook) and I don't want to find the smallest type that will fit my number so I'm just going whole hog.

2) I crammed some efficiencies into my prime finder function that I want to do more gracefully. The first is that if the number being tested is even it bails out, and the second is that in every loop it tests for how many divisors have come up without a remainder and bails out if it's more than two. I'll post the source after I clean it up.

3) The compiler gives me two warnings that I ignored (and hoped for the best).

What I AM happy about (other than getting the right answer) is that I am using two source files - one containing what I've pastebinned above, and another that just has my prime finding function that I wrote about in late January (plus a few optimisations). This is the first time I've written a program that uses two source files.

So, tomorrow I'll try to get a solid answer on why the square root trick works and then I'll start on problem 4.

No comments:

Post a Comment