forked from deutranium/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SieveOfEratosthenes.c
57 lines (46 loc) · 1022 Bytes
/
SieveOfEratosthenes.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
void sieveOfEratosthenes(int number)
{
int i, j;
int primes[number + 1];
for (i = 2; i <= number; i++) //populating array with naturals numbers
primes[i] = i;
i = 2;
while ((i * i) <= number)
{
if (primes[i] != 0)
{
for (j = 2; j < number; j++)
{
if (primes[i] * j > number)
break;
else
primes[primes[i] * j] = 0; // Instead of deleteing , making elemnets 0
}
}
i++;
}
int result[number + 1];
int k = 0;
for (i = 2; i <= number; i++)
{
//If number is not 0 then it is prime
if (primes[i] != 0)
{
result[k++] = primes[i];
}
}
for (i = 0; i < k; i++)
printf("%d ", result[i]);
printf("\n");
}
int main()
{
int number = 100;
sieveOfEratosthenes(number);
return 0;
}
/*
TIme Complexity : O(nlog(logn))
Space Complexity : O(n)
*/