use template based functions

This commit is contained in:
Krishna Vedala 2020-05-27 15:14:30 -04:00
parent 757970dbae
commit d262065492
No known key found for this signature in database
GPG Key ID: BA19ACF8FC8792F7

View File

@ -21,16 +21,17 @@
/** /**
* algorithm implementation for \f$a^b\f$ * algorithm implementation for \f$a^b\f$
*/ */
double fast_power_recursive(int64_t a, int64_t b) { template <typename T>
double fast_power_recursive(T a, T b) {
// negative power. a^b = 1 / (a^-b) // negative power. a^b = 1 / (a^-b)
if (b < 0) return 1.0 / fast_power_recursive(a, -b); if (b < 0) return 1.0 / fast_power_recursive(a, -b);
if (b == 0) return 1; if (b == 0) return 1;
int64_t bottom = fast_power_recursive(a, b >> 1); T bottom = fast_power_recursive(a, b >> 1);
// Since it is integer division b/2 = (b-1)/2 where b is odd. // Since it is integer division b/2 = (b-1)/2 where b is odd.
// Therefore, case2 is easily solved by integer division. // Therefore, case2 is easily solved by integer division.
int64_t result; double result;
if ((b & 1) == 0) // case1 if ((b & 1) == 0) // case1
result = bottom * bottom; result = bottom * bottom;
else // case2 else // case2
@ -42,7 +43,8 @@ double fast_power_recursive(int64_t a, int64_t b) {
Same algorithm with little different formula. Same algorithm with little different formula.
It still calculates in O(logN) It still calculates in O(logN)
*/ */
double fast_power_linear(int64_t a, int64_t b) { template <typename T>
double fast_power_linear(T a, T b) {
// negative power. a^b = 1 / (a^-b) // negative power. a^b = 1 / (a^-b)
if (b < 0) return 1.0 / fast_power_linear(a, -b); if (b < 0) return 1.0 / fast_power_linear(a, -b);