summaryrefslogtreecommitdiff
path: root/euler44.c
blob: db032aae0547c8db94afc1a8506c79e28afefc53 (plain)
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
#include <stdio.h>
#include <stdlib.h>

long long Pn(int n)
{
	return (long long)n*(long long)(3*n-1)/2;
}

#define MAXSIZE (1<<22)
long long P[MAXSIZE];

int comp(const void *a, const void *b)
{
	long long aa = *(long long*)a;
	long long bb = *(long long*)b;
	if (aa < bb)
		return -1;
	if (aa > bb)
		return 1;
	return 0;
}

int main()
{
	int i, j;
	int range = (1<<15);
	for (i = 1; i < range; i++)
		P[i] = Pn(i);

	/* i < 257 is impossible when searching with range=(1<<15) */
	/* i < 725 is impossible with range=(1<<18) */
	/* i < 1449 is impossible with range=(1<<20) */
	for (i = 1; i < range; i++) {
		long long diff = P[i];
		for (j = 1; j < range - 1; j++) {
			long long Pj = P[j];
			long long Pk = Pj + diff;
			long long Pjk = Pj + Pk;
			if (Pk < P[j+1])
				break;
			while (Pjk > P[range-1]) {
				int newrange = range * 2;
				int r;
				for (r = range; r < newrange; r++)
					P[r] = Pn(r);
				range = newrange;
			}
			if (!bsearch(&Pk, P+1, range-1, sizeof(long long), comp))
				continue;
			if (!bsearch(&Pjk, P+1, range-1, sizeof(long long), comp))
				continue;
			printf("i = %d, D = %lld, j = %d, P[j] = %lld\n", i, diff, j, Pj);
			/* i = 1912, D = 5482660, j = 1020, P[j] = 1560090 */
			return 0;
		}
		printf("i = %d\n", i);
	}
}