-
Notifications
You must be signed in to change notification settings - Fork 5
/
highly_divisible_triangular_number.c
68 lines (52 loc) · 1.24 KB
/
highly_divisible_triangular_number.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
/**
* Highly divisible traingular number.
* https://projecteuler.net/problem=12
*/
#include <math.h>
#include <stdlib.h>
#include <assert.h>
typedef struct FACTOR
{
int *factors;
int count;
} Factor;
Factor get_factors(int n)
{
int root = (int) sqrt(n);
int *factors = (int *) malloc((n / 2) * sizeof(int));
int j = 0;
for (int i = 1; i <= root; i++) {
if (n % i == 0) {
factors[j++] = i;
if (i != (n / i)) {
factors[j++] = n / i;
}
}
}
Factor factor = {
.factors = factors,
.count = j
};
return factor;
}
unsigned long highly_divisible_triangular_number(int divisors)
{
int factorCount = 0;
unsigned long triangularNumber = 1;
Factor factor;
unsigned long i = 1;
while (factorCount <= divisors) {
factor = get_factors((int) triangularNumber);
factorCount = factor.count;
triangularNumber += (++i);
free(factor.factors);
}
return triangularNumber - i;
}
int main()
{
assert(28 == highly_divisible_triangular_number(5));
assert(73920 == highly_divisible_triangular_number(100));
assert(76576500 == highly_divisible_triangular_number(500));
return 0;
}