![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Implement Sieve of eratosthenes to Generate Prime Numbers Between Given Range
This is C++ program to implement Sieve of Eratosthenes to Generate Prime Numbers Between Given Range. In this method, an integer array with all elements initializes to zero.
It follows where each non-prime element’s index is marked as 1 inside the nested loops. The prime numbers are those whose index is marked as 0.
Algorithm
Begin Declare an array of size n and initialize it to zero Declare length, i, j Read length For i = 2 to n-1 do For j = i*i to n-1 do Arr[j-1]=1 Done Done For i =1 to n do If(arr[i-1]==0) Print i Done End
Example Code
#include <iostream> const int len = 30; int main() { int arr[30] = {0}; for (int i = 2; i < 30; i++) { for (int j = i * i; j < 30; j+=i) { arr[j - 1] = 1; } } for (int i = 1; i < 30; i++) { if (arr[i - 1] == 0) std::cout << i << "\t"; } }
Output
1 2 3 5 7 11 13 17 19 23 29
Advertisements