-
Notifications
You must be signed in to change notification settings - Fork 0
/
project_euler_prob10.c
60 lines (50 loc) · 1.12 KB
/
project_euler_prob10.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
/*
* project_euler_prob10.c
*
* Created on: Aug 5, 2012
* Author: ssimmons
*
* Find sum of primes < 2*10^6
* Strategy: Using sieve of Eratosthenes
* to get primes, then sum.
*
* Note: Previous problem solved analytically before
* got around to writing a program that worked.
*
* Due to frustration, it will now not be written.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LENGTH 2000000
long int sumnums(int input[]);
int main(){
int *nums;
int i, j;
nums = (int *) malloc(sizeof(int)*LENGTH);
long int output;
nums[0] = 0;
nums[1] = 0;
for (i = 2; i<LENGTH; i++)
nums[i] = 1;
for (i = 2; i< ( (int) ceil(sqrt((double) LENGTH)) ); i++){
if(nums[i] == 1){
for(j=(i*i); j<LENGTH; j += i){ // j = i*i to start with as starting lower
nums[j] = 0; // already done by sieving other primes
}
}
}
output = sumnums(nums);
printf("The sum of all primes below 2 million is: %ld\n", output);
free(nums);
return 0;
}
long int sumnums(int input[]){
int i;
long int temp = 0;
for (i = 0; i<LENGTH; i++){
if(input[i] == 1)
temp += (long int) i;
}
return temp;
}