#include <iostream>
#include <vector>
#include <iomanip>
// return true if number is a prime number
// smaller_primes: the list of prime numbers smaller than this number
// vector: https://cal-linux.com/tutorials/vectors.htmlbool is_prime( int number, const std::vector<int>& smaller_primes )
{
// n is prime if it is not divisible by any smaller prime number
// range based loop: http://www.stroustrup.com/C++11FAQ.html#for
// (note: dividing by prime numbers up to the square root of n is sufficient)
for( int p : smaller_primes ) if( number%p == 0 ) returnfalse ;
returntrue ;
}
// return a vector containing the first n prime numbers
// vector: https://cal-linux.com/tutorials/vectors.html
std::vector<int> first_n_primes( std::size_t nprimes )
{
std::vector<int> prime_numbers_list( 1, 2 ) ; // initially just the one prime number 2
// for each odd number starting with 3, till n primes have been found
// (we know that even numbers greater than 2 are not prime)
for( int number = 3 ; prime_numbers_list.size() < nprimes ; number += 2 )
{
// add it to the list of prime numbers if it is a prime number
if( is_prime( number, prime_numbers_list ) ) prime_numbers_list.push_back(number) ;
}
return prime_numbers_list ;
}
// print the first n prime numbers
void print_first_n_primes( std::size_t nprimes )
{
constauto prime_number_list = first_n_primes(nprimes) ;
for( std::size_t i = 0 ; i < nprimes ; ++i )
{
std::cout << std::setw(6) << prime_number_list[i] ;
if( i%10 == 9 ) std::cout << '\n' ; // a new line after every 10 numbers
}
std::cout << '\n' ;
}
int main()
{
print_first_n_primes(1000) ; // print the first 1000 prime numbers
}
Use code tags, [.code] [./code] - Remove the periods and put your code between those so it's easier on the eyes.
You can put everything in a for loop like this:
1 2 3 4 5 6
cin >> n;
for(int i = n; i > 0; i--)
{
//Insert Prime# Loop
}
That will loop through the code you want to use for printing out prime numbers.
Or, if that doesn't go well with your code when you finish it, you can have a terminating if statement like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
cin >> n;
for (int i = 0; i < number; i++)
{
for (int j = 2; j <= n / 2; ++i)
{
//Whatever Code You End Up Writing
}
//Whatever Code You End Up Writing
n--;
if(n == 0)
break;
}