> I am not dismissing the advice. I am explaining exactly what I am doing.
You assume too much. We already know what you are
trying to do, and how... but you are failing for the exact reasons that
firedraco (and now
helios) have given. Not because
we misunderstand you or your code. Justifying yourself against the advice given you is dismissive, and a bit brash.
Though I am glad you appear to be thinking about the problem.
Helios The Sieve of Eratosthenes works by crossing-off numbers (which must be stored somehow --an array works nicely). The Wikipedia has a nice animation
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
(The instructions given by the professor were taken directly from the article.)
Helios is correct in that once you identify a prime, you can print it immediately --there is no need to have a separate display loop. But that doesn't really matter either way. (Your assignment was not specific about if and when you are supposed to print the primes, but the way you have it works best if you are to stop looping at sqrt(n).)
Firedraco said it correctly: you are not following the algorithm given you. You need to rethink the loops, and some variable names. Here are some hints:
1. Useful variable names:
1 2 3 4
|
int highestNumber; // user's input == size of array minus one
int squareRootOfHighestNumber; // when to stop the outer loop (see note below)
int currentPrime; // outer loop counter
int multipeOfCurrentPrime; // inner loop (mega-hint: Wow your professor!)
|
I give these names to help you think a little more clearly about the algorithm. For example,
highestNumber is better than
upperRange because it is more explicit, doesn't mix terminologies, and doesn't imply the wrong thing for the array size.
2. Use one outer loop and
two inner loops. Steps 3 and 4 are each an inner loop (step 2 is actually the same as step 4 --the difference is just that 2 is the very first prime; you don't need a step 3 to find it). Step 5 is the outer loop.
3. Notes: you don't actually have to calculate the square root of the highest number. If your currentPrime
2 > highestNumber then you are done. Either method will do. (I would use the extra variable --just because I'm an optimization freak-- instead of doing an extra multiplication each time through the loop's test.)
Hmm, I think that should have answered your question... (I actually started this early this morning --then took a six-hour break to watch my niece --and only now did I finish... Some lossage may have occurred.) :-P
Good luck.