forked from libtom/libtommath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbn_mp_fibonacci.c
98 lines (93 loc) · 2.21 KB
/
bn_mp_fibonacci.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <tommath.h>
#ifdef BN_MP_FIBONACCI_C
/* max n = 47 */
static unsigned long _fibonacci(unsigned long n)
{
unsigned long i = 1, j = 0, k, l;
for (k = 1; k <= n; k++) {
l = i + j;
i = j;
j = l;
}
return j;
}
/* matrix expo. */
int mp_fibonacci(unsigned long n, mp_int *r)
{
unsigned long i = n - 1;
mp_int a, b, c, d, t, t1, t2, t3;
int e;
if (n < 45) {
mp_set_int(r,_fibonacci(n));
return MP_OKAY;
}
if ((e = mp_init_multi(&a, &b, &c, &d, &t, &t1, &t2, &t3, NULL)) != MP_OKAY) {
return e;
}
mp_set(&a, (mp_digit) 1);
mp_set(&b, (mp_digit) 0);
mp_set(&c, (mp_digit) 0);
mp_set(&d, (mp_digit) 1);
while (i > 0) {
if (i & 0x1) {
//t = d*(a + b) + c*b;
if ((e = mp_mul(&c, &b, &t1)) != MP_OKAY) {
return e;
}
if ((e = mp_add(&a, &b, &t2)) != MP_OKAY) {
return e;
}
if ((e = mp_mul(&d, &t2, &t3)) != MP_OKAY) {
return e;
}
if ((e = mp_add(&t3, &t1, &t)) != MP_OKAY) {
return e;
}
//a = d*b + c*a;
if ((e = mp_mul(&d, &b, &t1)) != MP_OKAY) {
return e;
}
if ((e = mp_mul(&c, &a, &t2)) != MP_OKAY) {
return e;
}
if ((e = mp_add(&t1, &t2, &a)) != MP_OKAY) {
return e;
}
//b = t;
if ((e = mp_copy(&t, &b)) != MP_OKAY) {
return e;
}
}
//t = d*(2*c + d);
if ((e = mp_mul_2d(&c, 1, &t1)) != MP_OKAY) {
return e;
}
if ((e = mp_add(&t1, &d, &t2)) != MP_OKAY) {
return e;
}
if ((e = mp_mul(&d, &t2, &t)) != MP_OKAY) {
return e;
}
//c = c*c + d*d;
if ((e = mp_sqr(&c, &t1)) != MP_OKAY) {
return e;
}
if ((e = mp_sqr(&d, &t2)) != MP_OKAY) {
return e;
}
if ((e = mp_add(&t1, &t2, &c)) != MP_OKAY) {
return e;
}
//d = t;
if ((e = mp_copy(&t, &d)) != MP_OKAY) {
return e;
}
i /= 2;
}
if ((e = mp_add(&a, &b, r)) != MP_OKAY) {
return e;
}
mp_clear_multi(&a, &b, &c, &d, &t, &t1, &t2, &t3, NULL);
return MP_OKAY;
}
#endif