-
Notifications
You must be signed in to change notification settings - Fork 3
/
factorize.h
105 lines (88 loc) · 1.9 KB
/
factorize.h
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#ifndef FACTORIZE_H
#define FACTORIZE_H
#include <stdbool.h>
// Code adapted from gsl/fft/factorize.c
void factorize (const int n,
int *n_factors,
int factors[],
int * implemented_factors)
{
int nf = 0;
int ntest = n;
int factor;
int i = 0;
if (n == 0)
{
printf("Length n must be positive integer\n");
return ;
}
if (n == 1)
{
factors[0] = 1;
*n_factors = 1;
return ;
}
/* deal with the implemented factors */
while (implemented_factors[i] && ntest != 1)
{
factor = implemented_factors[i];
while ((ntest % factor) == 0)
{
ntest = ntest / factor;
factors[nf] = factor;
nf++;
}
i++;
}
// Ok that's it
if(ntest != 1)
{
factors[nf] = ntest;
nf++;
}
/* check that the factorization is correct */
{
int product = 1;
for (i = 0; i < nf; i++)
{
product *= factors[i];
}
if (product != n)
{
printf("factorization failed");
}
}
*n_factors = nf;
}
bool is_optimal(int n, int * implemented_factors)
{
// We check that n is not a multiple of 4*4*4*2
if(n % 4*4*4*2 == 0)
return false;
int nf=0;
int factors[64];
int i = 0;
factorize(n, &nf, factors,implemented_factors);
// We just have to check if the last factor belongs to GSL_FACTORS
while(implemented_factors[i])
{
if(factors[nf-1] == implemented_factors[i])
return true;
++i;
}
return false;
}
int find_closest_factor(int n, int * implemented_factor)
{
int j;
if(is_optimal(n,implemented_factor))
return n;
else
{
j = n+1;
while(!is_optimal(j,implemented_factor))
++j;
return j;
}
}
#endif