mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
use template based functions
This commit is contained in:
parent
757970dbae
commit
d262065492
@ -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);
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user