-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem46.c
75 lines (63 loc) · 1.2 KB
/
problem46.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
/*
* Copyright (c) 2009, eagletmt
* Released under the MIT License <http://opensource.org/licenses/mit-license.php>
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define N 10000
static int is_square(unsigned n);
static char *prime_sieve(unsigned n);
int main(void)
{
char *sieve = prime_sieve(N);
unsigned *primes = malloc(sizeof(unsigned) * N);
unsigned i, j = 0;
for (i = 0; i < N; i++) {
if (!sieve[i]) {
primes[j++] = i;
}
}
primes[j] = 0;
for (i = 3; i < N; i += 2) {
if (!sieve[i]) {
/* skip if i is prime */
continue;
}
for (j = 0; primes[j]; j++) {
unsigned s;
if (primes[j] > i) {
printf("%u\n", i);
goto FINISH;
}
s = (i - primes[j])/2;
if (is_square(s)) {
break;
}
}
}
FINISH:
free(sieve);
free(primes);
return 0;
}
char *prime_sieve(unsigned n)
{
char *sieve = calloc(n, sizeof *sieve);
unsigned i;
sieve[0] = sieve[1] = 1;
for (i = 2; i < n; i++) {
if (!sieve[i]) {
unsigned j;
for (j = i*2; j < n; j += i) {
sieve[j] = 1;
}
}
}
return sieve;
}
int is_square(unsigned n)
{
unsigned sq = sqrt(n);
return sq*sq == n;
}