Thursday, September 29, 2011

Project Euler - Problem Seven

This one took a little extra input from good ole Michael. Apparently, me and prime numbers just don't get along very well. It's like we hate each other without even knowing it. Here's the problem:
With Michael's help, I managed to get it done though. It's really fairly simple, so I'm going to just do like regular and put a few screenshots up.

After discussion with Michael, we decided that it would be best to have a list of the primes we've found so far. It'll start off primed with two and three. Everything after that will be found via the program. It'll do a number mod everything currently in the list of primes. If it isn't divisible by any of the primes, then that number is added to the list and it moves on to the next number.

This seems to work pretty well, considering that it doesn't take very long at all to run. It's pretty cool to put a little cout statement to print out primes as they're found. I've got on in my code here. It lets me know if it's working too!

So here are my functions:
primelist_zero simply zeros out the list of primes. I did this so that I can have loops that run while elements in the list are or aren't zero. There's probably a better way to do it, but this one works.
Next there's the is_prime function. The name on this one is pretty telling about its function. It just checks whether or not a number is prime.
You're starting with an increment of zero each time the function is called. This increment variable is used to know which element of primeList to mod by. If the number mod by any number in the primeList equals zero, then it exits the function call. Otherwise, it adds one to the increment variable and checks again.  It does that until it gets to an empty spot in the primeList, at which point the number has to be prime.

These functions are wrapped up in a nice little main:
If you've got any problems, feel free to ask!

No comments:

Post a Comment