-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpythagorean.c
74 lines (60 loc) · 1.52 KB
/
pythagorean.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
// Licensed under the MIT License.
#include <math.h>
#include <stdlib.h>
#include "euclidean.h"
#include "pythagorean_iterator.h"
int* pythagorean_count_range(long max)
{
int* result = calloc(max, sizeof * result);
if (!result)
{
return NULL;
}
long end = sqrt(max);
for (long m = 1; m < end; m += 2)
{
for (long n = 2; n < end; n += 2)
{
if (gcd(m, n) != 1)
{
continue;
}
long sum = labs(m * m - n * n) + m * m + n * n + 2 * m * n;
for (long kSum = sum; kSum < max; kSum += sum)
{
result[kSum]++;
}
}
}
return result;
}
void pythagorean_begin(PythagoreanIterator iterator, long max)
{
iterator->c = 2;
iterator->m = 0;
iterator->n = 1;
iterator->max = max;
iterator->sqrtMax = sqrt(max);
iterator->end = false;
pythagorean_next(iterator);
}
void pythagorean_next(PythagoreanIterator iterator)
{
while (iterator->m < iterator->max)
{
while (iterator->n < iterator->m)
{
iterator->a = iterator->m * iterator->m - iterator->n * iterator->n;
iterator->b = 2 * iterator->m * iterator->n;
iterator->c = iterator->m * iterator->m + iterator->n * iterator->n;
iterator->n++;
if (iterator->c < iterator->max)
{
return;
}
}
iterator->m++;
iterator->n = 1;
}
iterator->end = true;
}