You have an odd variation: usually the requirement is to display all primes less than (or equal to) the input number. But either way your issue is the same:
The
sieve of Eratosthenes is a well-known way to filter out non-prime numbers.
You can do this yourself. Create an array. It doesn't matter what kind of array it is (boolean, integer, whatever, so long as it can indicate 'prime' and 'not prime') — what is important are the
indexes into the array. The array should be from 0 to 102.
bool primes[103] = { true };
Remove zero and one. (Neither are prime.)
primes[0] = primes[1] = false;
Now you need a loop from 2 to 102. (Technically, you can stop sooner. This is an upgrade left as an exercise for you.)
1 2 3
|
for (int n = 2; n < 102; n++)
{
}
|
Inside your loop you will need to do the following:
• First, check if the current index is prime.
(
primes[2]
will be
true
, so we know it is prime.)
• If it is not, you are done with this loop; continue to the next iteration of the outer loop.
• If it is prime, then use another loop to remove all multiples of this index from the
primes[]
.
In the case of index 2, we will mark
primes[4]
as
false
,
and we will mark
primes[6]
as
false
, and
primes[8]
, and
primes[10]
, and so on until we get to 102.
When you are done, the
primes[]
array will have
true
s only at indices that are prime.
When you print the primes is up to you. You can print it in the loop above when you check if the current index is prime, or you can finish that and create a new loop over
primes[]
and only print
n
for each
primes[n]
that is 'prime' (or true).
There are other ways of doing this.
One way is to keep a list/set/whatever of
found prime numbers,
adding a new number only if no element in the list/set/whatever evenly divides the potentially new number. (You still need to count sequentially though.)
Hope this helps.