C++ Program to Implement Sieve of Eratosthenes

«
»
This C++ program to implement Sieve of Eratosthenes. The program initializes an integer array with all the elements initialized to 0. Then the algorithm follows where the each non-prime element’s index is marked as 1 inside the nested loops. The prime numbers are those whose value of index is marked as 0.

Here is the source code of the C++ program illustrates how to pass a variable to a function by value. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to implement Sieve of Eratosthenes
  3.  */
  4.  
  5. #include <iostream>
  6. const int len = 100;
  7.  
  8. int main()
  9. {
  10.     int arr[100] = {0};
  11.  
  12.     for (int i = 2; i < 100; i++)
  13.     {
  14.         for (int j = i * i; j < 100; j+=i)
  15.         {
  16.             arr[j - 1] = 1;
  17.         }
  18.     }
  19.     for (int i = 1; i < 100; i++)
  20.     {
  21.         if (arr[i - 1] == 0)
  22.             std::cout << i << "\t";
  23.     }
  24. }

$ a.out
1       2       3       5       7       11      13      17      19      23
29      31      37      41      43      47      53      59      61      67
71      73      79      83      89      97

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.