Website Summary Files Commits Branches @commit @diff @stats
path: root / Sem. 06 / sieveOfEratosthenes.cpp
diff options
context:
space:
mode:
1 files changed, 48 insertions, 0 deletions
-rw-r--r--Sem. 06/sieveOfEratosthenes.cpp48
diff --git a/Sem. 06/sieveOfEratosthenes.cpp b/Sem. 06/sieveOfEratosthenes.cpp
new file mode 100644
index 0000000..2505ad9
--- /dev/null
+++ b/Sem. 06/sieveOfEratosthenes.cpp
@@ -0,0 +1,48 @@
+#include <iostream>
+using namespace std;
+
+void init(bool arr[], unsigned size, bool value)
+{
+ for (unsigned i = 0; i < size; i++)
+ arr[i] = value;
+}
+
+void sieveEratosthenes(bool arr[], unsigned size)
+{
+ arr[0] = arr[1] = false;
+
+ for (unsigned i = 2; i < size; i++)
+ {
+ if (!arr[i]) //ако числото е задраскано
+ continue;
+
+ for (unsigned iter = i + i; iter < size; iter += i)
+ arr[iter] = false; //задраскваме
+ }
+}
+
+void printSieve(const bool arr[], unsigned size)
+{
+ for (unsigned i = 0; i < size; i++)
+ {
+ if (arr[i])
+ {
+ cout << i << " ";
+ }
+ }
+}
+
+
+int main()
+{
+ const unsigned MAX_SIZE = 1000;
+ bool arr[MAX_SIZE];
+
+ int n;
+ cin >> n;
+
+ init(arr, n, true);
+ sieveEratosthenes(arr, n);
+ printSieve(arr, n);
+}
+