-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsieve_of_eratosthenes.c
67 lines (41 loc) · 1.23 KB
/
sieve_of_eratosthenes.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
58
59
60
61
62
63
64
65
66
67
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
* The Program finds prime numbers equal or less then the given number and prints those.
*/
void print_primes(int* number_array,int size){
//print primes with a space
for(int i=0;i<=size;i++){
if(number_array[i]==0){
printf("%d ",i);
}
}
}
int main(void) {
int size,*number_array;
printf("enter a number\n");
scanf("%d",&size);
//creates an array index from 0 to given number
number_array=(int*)calloc(size+1,sizeof(int));
//according to axioms they are not prime
number_array[0]=1;
number_array[1]=1;
//starts with first prime '2'
for(int i=2;i<=sqrt(size);i++){
//if the number is not prime, pass.
if(number_array[i]==0){
int counter=2;
//searches for the numbers which are divided by 'i'
while(counter*i<=size){
//if a number is not prime, it makes number_array[number] value 1
number_array[counter*i]=1;
counter++;
}
}
}
//prime indexes of number_array have value 0, others have 1
print_primes(number_array,size);
free(number_array);
return 0;
}