Logic behind a prime number is not c++ it is math.
There are several ways. THe most efficient wya is to use Sieve. Which states this:
To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method:
Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n).
Initially, let p equal 2, the first prime number.
Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. These will be multiples of p: 2p, 3p, 4p, etc.; note that some of them may have already been marked.
Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
which would look something liek this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
#include <vector>
int main()
{
int min( 0 ) , max( 0 );
std::cout << "min: " << std::flush;
std::cin >> min;
std::cout << "max: " << std::flush;
std::cin >> max;
std::vector<int> primes( 0 );
for( int i( 2 ); i < max; ++i )
{
primes.push_back( i );
}
auto it( primes.begin() );
while( it != primes.end() )
{
for( auto it2( it + 1); it2 != primes.end(); ++it2 )
{
if( *it2 % *it == 0 )
{
primes.erase( it2 );
--it2;
}
}
++it;
}
for( const auto &it : primes )
{
if( it >= min ) std::cout << it << std::endl;
}
}
|
Which runs extremely fast especially if you put in the min/max yourself with out using ifstream for that.