Having two issues with this code. First, I need it to display the last 20 prime numbers. Currently it shows me the first 20 (this is probably an easy fix but I'm stumped at the moment). Secondly, the program is displaying 25 numbers instead of just 20 and I have no clue why. Any help would be greatly appreciated!
If you need the last 20, then you have to have the primes before you show any of them. That is, you have to store them until you know that you have the last 20.
#include <iostream>
#include <vector>
constexpr size_t ToDisplay {20};
constexprunsigned Low {30};
constexprunsigned High {2000};
bool isPrime(unsigned value) {
for (unsigned i {3}; i * i <= value; i += 2)
if (value % i == 0)
returnfalse;
returntrue;
}
int main() {
std::cout << "Prime Number Finder\n";
for (unsigned num {1}; num; ) {
do {
std::cout << "\nPlease enter an integer between " << Low << " and " << High << " (0 to exit) : ";
std::cin >> num;
} while ((num != 0 && (num < Low || num > High)) && (std::cout << "Number not in range\n"));
if (num) {
std::vector<unsigned> table {2};
for (unsigned i {3}; i < num; i += 2)
if (isPrime(i))
table.push_back(i);
for (auto it {table.size() > ToDisplay ? table.end() - ToDisplay : table.begin()}; it < table.end(); ++it)
std::cout << table.size() - (table.end() - it) + 1 << '\t' << *it << '\n';
}
}
}
#include <iostream>
#include <valarray>
#include <numeric>
usingnamespace std;
slice betterSlice( int low, int high, int stride ){ return slice( low, ( high - low ) / stride + 1, stride ); }
valarray<int> sieve( int N )
{
valarray<int> A(1+N);
iota( begin(A), end(A), 0 ); A[1] = 0;
if ( N >= 4 ) A[ betterSlice( 4, N, 2 ) ] = 0;
for ( int i = 3; i * i <= N; i += 2 ) if ( A[i] ) A[ betterSlice( i*i, N, 2*i ) ] = 0;
return A[A>0];
}
int main()
{
int high = 2000, num = 20;
auto primes = sieve( high );
cout << "The last " << num << " primes before " << high << " are\n";
for ( int i = num; i; i-- ) cout << primes[primes.size()-i] << '\n';
}