Hi,
Can we ask you to edit your original post, select al the code, then press the <> button, so it uses code tags?
Your code should look like this:
1 2 3 4 5 6
|
#include <iostream>
#include <cmath>
using namespace std;
bool IsPrime(int number)
|
I took a different approach to this problem:
I put 2, into a std::list, then all the odd numbers from 3 to 2,000,001.
LIMIT = 2000000
then I remove all multiples of 3.
The next number in the list is 5, so I remove all multiples of it.
And so on, for each next number in the list, until
sqrt(LIMIT)
The good thing about this algorithm is that the amount of remaining numbers reduces quickly.
I got this to work up to 2 million in less than 1 second. Remember it's finding all the primes.
Once you have the list, it is quick to see if a specific number is in the list.
However there are some inefficiencies. Say we are checking for multiples of some prime around 1001, we shouldn't need to check every number that remains in the list. But multiples of 1001 might have already been removed from the list.
Edit in fact all the multiples of all the numbers less than 1001 are already gone. so we only need to start from 1001
2.
I am not sure whether another container might be better,
std::unordered_list
maybe ? Not sure how good that is when it has to access every item.
std::vector
is no good IMO, even with move semantics, if 1 item is removed then all the others have to be moved along 1. Might be wrong about that though.
Hope this helps :+)