Anyway, part of the code I ended up with was this:
long i = primeList[primeList.Count - 1];
bool foundPrime = false;
while (!foundPrime)
{
i += 2;
foundPrime = true;
foreach (long prime in primeList)
{
if (i % prime == 0)
{
foundPrime = false;
break;
}
}
}
primeList.Add(i);
What this does is it sets i to the highest discovered prime and then increments it by 2 in each loop. It checks if that number is a prime by seeing if it's evenly divisible by any previously discovered (lower number) primes. If it's not divisible by any prime numbers smaller than itself, we know it's prime, and we add it to the prime list.
Now, this algorithm works. So I don't need help with that... but it's ugly. I hate how I set the boolean flag to false to test for it, set it to true at the beginning of the loop, and then set it back to false if the number being tested turns out to not be prime.
If it was just this once, I wouldn't be bothered by it, but I've used this construction on a couple other problems too (not for primes, but other problems where I set a bool to false outside a loop, true at the beginning of it, and running some tests inside the loop and set the bool back to false if the tests fail). Anyway, I know there must be a more elegant way to phrase this... so, anyone want to tell me what it is?
This post has been edited by pharylon: 11 March 2013 - 06:51 PM

New Topic/Question
Reply


MultiQuote



|