Skip to content

Commit f7d6c73

Browse files
committed
solve problem 50
1 parent 364058c commit f7d6c73

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

problem_026-050/problem_050.c

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include <stdio.h>
2+
#include <stdint.h>
3+
#include <stdlib.h>
4+
5+
#define N 1000000
6+
7+
uint8_t sieve[N];
8+
9+
/* init_sieve: initialize the array to test if a number is prime */
10+
void init_sieve(void)
11+
{
12+
int32_t i, j;
13+
14+
for (i = 0; i < N; ++i)
15+
sieve[i] = 1;
16+
sieve[0] = sieve[1] = 0;
17+
18+
for (i = 2; i < N; ++i)
19+
if (sieve[i])
20+
for (j = 2*i; j < N; j += i)
21+
sieve[j] = 0;
22+
}
23+
24+
/* find_longest_prime_sum: find the prime number that can be written with the
25+
* longest sum of consecutive primes */
26+
int32_t find_longest_prime_sum(void)
27+
{
28+
int32_t i, j, n_primes, longest_length, longest_sum, sum, *primes;
29+
30+
/* count number of primes */
31+
n_primes = 0;
32+
for (i = 0; i < N; ++i)
33+
if (sieve[i])
34+
++n_primes;
35+
36+
/* regroup primes into a single array */
37+
primes = malloc(sizeof *primes * n_primes);
38+
for (i = j = 0; i < N; ++i)
39+
if (sieve[i])
40+
primes[j++] = i;
41+
42+
longest_sum = longest_length = 0;
43+
for (i = 0; i < n_primes; ++i)
44+
{
45+
sum = 0;
46+
for (j = i; j < n_primes; ++j)
47+
{
48+
sum += primes[j];
49+
50+
if (sum > N)
51+
break;
52+
53+
/* current sum is a prime and longer than current known
54+
* longest sequence. Save its statistics. */
55+
if (sieve[sum] && j - i > longest_length)
56+
{
57+
longest_length = j - i;
58+
longest_sum = sum;
59+
}
60+
}
61+
}
62+
63+
return longest_sum;
64+
}
65+
66+
int32_t main(void)
67+
{
68+
init_sieve();
69+
printf("Problem 50: %d\n", find_longest_prime_sum());
70+
71+
return 0;
72+
}

0 commit comments

Comments
 (0)