fork download
  1. #include <iostream>
  2. #include <math.h>
  3. using namespace std;
  4.  
  5. const int MAXN = 1e7;
  6. int prime[MAXN]; // Array to store prime status of numbers up to 10^7
  7.  
  8. void sieve() {
  9. // Step 1: Assume all numbers are prime
  10. for (int i = 0; i <= MAXN; i++) {
  11. prime[i] = 1;
  12. }
  13.  
  14. // Step 2: Mark 0 and 1 as non-prime
  15. prime[0] = prime[1] = 0;
  16.  
  17. // Step 3: Sieve process
  18. for (int i = 2; i <= sqrt(MAXN); i++) {
  19. if (prime[i]) { // If i is still prime
  20. for (int j = i * i; j <= MAXN; j += i) {
  21. prime[j] = 0; // Mark multiples of i as non-prime
  22. }
  23. }
  24. }
  25. }
  26.  
  27. int main() {
  28. sieve();
  29. int n;
  30. cin >> n;
  31. // Print prime numbers up to n
  32. for (int i = 0; i <= n; i++) {
  33. if (prime[i]) {
  34. cout << i << " ";
  35. }
  36. }
  37.  
  38. return 0;
  39. }
  40.  
Success #stdin #stdout 0.13s 42516KB
stdin
10
stdout
2 3 5 7