-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum_of_primes.c
84 lines (68 loc) · 1.43 KB
/
sum_of_primes.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct
{
double *array;
size_t size;
} Array;
void add_element(Array *a, double new_element)
{
a->size += 1;
a->array = (double *)realloc(a->array,a->size * sizeof(double));
a->array[a->size-1] = new_element;
// printf("array size = %d\n", (int)a->size);
}
void freeArray(Array *a)
{
free(a->array);
a->array = NULL;
}
int modulo_op(double a, double b)
{
return (int)(a - b*floor(a/b));
}
int main()
{
double i;
int j,k;
Array prime_factors;
prime_factors.array = (double *)malloc(0);
prime_factors.size = 0;
for (i = 2; i < 2000000; i=i+1)
{
// printf("%d\n", i);
if (prime_factors.size == 0)
{
add_element(&prime_factors,i);
// printf("array[0] = %d\n", prime_factors.array[0]);
}
else
{
// printf("here\n");
for (j = 0; j < prime_factors.size; j++)
{
// printf("i = %d, prime_factors.array[j] = %d, i %% prime_factors.array[j] = %d\n", i,
// prime_factors.array[j], i % prime_factors.array[j]);
if (modulo_op(i,prime_factors.array[j]) == 0)
{
break;
}
}
if (j == prime_factors.size)
{
add_element(&prime_factors, i);
printf("prime = %d\n", (int)i);
// sleep(0.5);
}
}
}
// printf("10001st prime factor = %f\n", i);
double sum = 0;
for (j = 0; j < prime_factors.size; j++){
sum += prime_factors.array[j];
}
freeArray(&prime_factors);
printf("sum = %f\n", sum);
return 0;
}