A very simple algorithm for your needs:
• Declare variables to hold the prime limit (the number till you want the prime numbers to be generated) and a flag which indicates whether a prime number was found or not (a boolean variable).
• Since while checking for primes we normally say that if a number is divisible by only 2 and itself then its a prime number. We can use a short cut here by considering that if a number is not divisible by any number between 2 and its square root, its a prime number.
• To achieve the above task, we would be needing two loops, one to generate all the numbers and the other for testing the numbers.
• Run the outer loop from 2 to the LIMIT and let the control variable (loop variable) be i.
• Run an inner loop with control variable j, where j starts from 2 and the loop runs till the square of i is less than or equal to j (short cut method)
• Inside the nested loops test whether i is completely divisible by j ( i % j = 0 ) .
• If the above condition is true, then we can conclude that the number is not prime. In this case, set the prime found flag to false and break out of the inner loop.
• After breaking out of the loop test whether we ducked out of the loop due to the condition failure or because of natural loop completion.
• If we broke out of the loop naturally, then the number i under consideration is prime. So print it.
• If we broke out of loop because of condition failure then the number "i" is not prime and so reset the flag.
• At the end of both the loops we would have a list of all the prime numbers.
Here is a sample:
#include <iostream>
int main ()
{
using namespace std ;
int limit = 0, prime_count = 0 ;
bool is_prime = true ;
cout << "Prime numbers till what? " ;
cin >> limit ;
getchar( ) ;
for( int i = 2; i < limit; ++i )
{
for( int j = 2; j * j <= i; ++j )
{
if ( i % j == 0 )
{
is_prime = false ;
break ;
}
}
if( is_prime )
{
++prime_count ;
cout << i << '\n' ;
}
else
{
is_prime = true ;
}
}
cout << "\nTotal of " << prime_count << " prime numbers were found." ;
getchar( ) ;
return 0 ;
}