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';
}
}
}
Prime Number Finder
Please enter an integer between 30 and 2000 (0 to exit) : 1500
220 1373
221 1381
222 1399
223 1409
224 1423
225 1427
226 1429
227 1433
228 1439
229 1447
230 1451
231 1453
232 1459
233 1471
234 1481
235 1483
236 1487
237 1489
238 1493
239 1499
Please enter an integer between 30 and 2000 (0 to exit) : 0
#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';
}
The last 20 primes before 2000 are
1861
1867
1871
1873
1877
1879
1889
1901
1907
1913
1931
1933
1949
1951
1973
1979
1987
1993
1997
1999