1//sieve of eratosthenes or prime of sieve
2#include<iostream>
3#include<math.h>
4using namespace std;
5void primeofsieve(long long int n)
6{
7 long long int arr[n]={};
8 for(int i=2;i<=sqrt(n);i++)
9 {
10 for(long long int j=i*i;j<=n;j+=i)
11 arr[j]=1;
12 }
13 for(long long int i=2;i<=n;i++)
14 {
15 if(arr[i]==0)
16 cout<<i<<" ";
17 }
18
19
20}
21int main()
22{
23
24 #ifdef _DEBUG
25 freopen("input.txt", "r", stdin);
26 freopen("output.txt", "w", stdout);
27 #endif
28 long long int n;
29 cin>>n;
30 cout<<"PRIME NUMBERs ARE : ";
31 primeofsieve(n);
32 return 0;
33}
1int n;
2vector<bool> is_prime(n+1, true);
3is_prime[0] = is_prime[1] = false;
4for (int i = 2; i <= n; i++) {
5 if (is_prime[i] && (long long)i * i <= n) {
6 for (int j = i * i; j <= n; j += i)
7 is_prime[j] = false;
8 }
9}
10
1// C++ program to print all primes smaller than or equal to
2// n using Sieve of Eratosthenes
3#include <bits/stdc++.h>
4using namespace std;
5
6void SieveOfEratosthenes(int n)
7{
8 // Create a boolean array "prime[0..n]" and initialize
9 // all entries it as true. A value in prime[i] will
10 // finally be false if i is Not a prime, else true.
11 bool prime[n+1];
12 memset(prime, true, sizeof(prime));
13
14 for (int p=2; p*p<=n; p++)
15 {
16 // If prime[p] is not changed, then it is a prime
17 if (prime[p] == true)
18 {
19 // Update all multiples of p greater than or
20 // equal to the square of it
21 // numbers which are multiple of p and are
22 // less than p^2 are already been marked.
23 for (int i=p*p; i<=n; i += p)
24 prime[i] = false;
25 }
26 }
27
28 // Print all prime numbers
29 for (int p=2; p<=n; p++)
30 if (prime[p])
31 cout << p << " ";
32}
33
34// Driver Program to test above function
35int main()
36{
37 int n = 30;
38 cout << "Following are the prime numbers smaller "
39 << " than or equal to " << n << endl;
40 SieveOfEratosthenes(n);
41 return 0;
42}
43
1int n;
2vector<char> is_prime(n+1, true);
3is_prime[0] = is_prime[1] = false;
4for (int i = 2; i <= n; i++) {
5 if (is_prime[i] && (long long)i * i <= n) {
6 for (int j = i * i; j <= n; j += i)
7 is_prime[j] = false;
8 }
9}
10
1#include <iostream>
2const int len = 30;
3int main() {
4 int arr[30] = {0};
5 for (int i = 2; i < 30; i++) {
6 for (int j = i * i; j < 30; j+=i) {
7 arr[j - 1] = 1;
8 }
9 }
10 for (int i = 1; i < 30; i++) {
11 if (arr[i - 1] == 0)
12 std::cout << i << "\t";
13 }
14}