fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstring>
  4. using namespace std;
  5.  
  6. // This function return vector of primes unsigned integer
  7. vector<unsigned> getPrimes ( unsigned from, unsigned to ) { // both inclusive
  8. vector<unsigned> primes; // declaration of result vector
  9. bool *isprime = new bool[ to+1 ]; // creating sieve of Eratosthenes
  10. memset ( isprime, 0xFF, to ); // setting all marks as true so every number now is prime
  11. unsigned n = 2; // start from 2 becouse 1 obviously prime (or not prime - it's not a actual question here)
  12. for ( ; n*n <= to; n++ ) { // cycle throught all integers (lesser or equal than 'to')
  13. if ( isprime[ n ] ) { // if 'n' actualy is prime
  14. for ( unsigned i = n*n; i <= to; i += n ) { // than cycle throght all divisible by 'n' greater than square of 'n'
  15. isprime[ i ] = false; // and mark them as non-prime
  16. }
  17.  
  18. if ( n > from ) { // also, if one included by range
  19. primes.push_back ( n ); // push it back into vector
  20. }
  21. }
  22. } // end of sieve
  23.  
  24. n = std::max ( n, from ); // and, after sieve
  25. for ( ; n <= to; n++ ) { // we go to the end of our range
  26. if ( isprime[ n ] ) { // in order to catch all remaining primes
  27. primes.push_back ( n ); // and push it back into vector
  28. }
  29. }
  30.  
  31. return primes; // as final - return vector of primes
  32. }
  33.  
  34. int main () {
  35. int line = 0; // just set it to -1 if you want to miss print line-breaker
  36. // cycle below just prints primes
  37. for ( auto prime: getPrimes ( 100, 500 ) ) {
  38. cout << prime << " ";
  39. if ( line != -1 ) {
  40. line++;
  41. if ( !(line%5) ) cout << endl; // end line-breaker, if line != -1
  42. }
  43. }
  44.  
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
101 103 107 109 113 
127 131 137 139 149 
151 157 163 167 173 
179 181 191 193 197 
199 211 223 227 229 
233 239 241 251 257 
263 269 271 277 281 
283 293 307 311 313 
317 331 337 347 349 
353 359 367 373 379 
383 389 397 401 409 
419 421 431 433 439 
443 449 457 461 463 
467 479 487 491 499