-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmath.cpp
88 lines (71 loc) · 2.13 KB
/
math.cpp
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
#ifndef APA_MATH_CPP
#define APA_MATH_CPP
#include "math.hpp"
namespace apa {
template <class T>
T fibonacci_template(size_t nth, T b0, T b1) {
T base0 = b0, base1 = b1;
T nthfib = 0;
for (size_t i = 2; i < nth; ++i) {
nthfib = base0 + base1;
base0 = std::move(base1);
base1 = std::move(nthfib);
}
return base0 + base1;
}
template <class T>
T factorial_template(size_t n) {
T factorial(1);
T iter = factorial;
for (size_t i = 1; i <= n; ++i) {
factorial *= iter;
iter++;
}
return factorial;
}
integer fibonacci_integer(size_t nth, integer b0, integer b1) {
if (nth < 2) {
return __INTEGER_ONE;
}
return fibonacci_template<integer>(nth, b0, b1);
}
bint fibonacci(size_t nth, bint b0, bint b1) {
if (nth < 2) {
return __BINT_ONE;
}
return fibonacci_template<bint>(nth, b0, b1);
}
integer factorial_integer(size_t n) {
return factorial_template<integer>(n);
}
bint factorial(size_t n) {
return factorial_template<bint>(n);
}
integer power_integer(const integer &base, const integer &exponent) {
if (exponent == __INTEGER_ZERO) {
return __INTEGER_ONE;
} else if (exponent == __INTEGER_ONE) {
return base;
}
integer sub_power = power_integer(base, exponent / __INTEGER_TWO);
if ((exponent % __INTEGER_TWO) == __INTEGER_ZERO) {
return sub_power * sub_power;
} else {
return base * sub_power * sub_power;
}
}
bint power(const bint &base, const bint &exponent) {
if (exponent == __BINT_ZERO) {
return __BINT_ONE;
} else if (exponent == __BINT_ONE) {
return base;
}
bint sub_power = power(base, exponent / __BINT_TWO);
if ((exponent % __BINT_TWO) == __BINT_ZERO) {
return sub_power * sub_power;
} else {
return base * sub_power * sub_power;
}
}
} // namespace apa
#endif