TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
fast_power.cpp
Go to the documentation of this file.
1
15#include <cassert>
16#include <cmath>
17#include <cstdint>
18#include <cstdlib>
19#include <ctime>
20#include <iostream>
21
25template <typename T>
26double fast_power_recursive(T a, T b) {
27 // negative power. a^b = 1 / (a^-b)
28 if (b < 0)
29 return 1.0 / fast_power_recursive(a, -b);
30
31 if (b == 0)
32 return 1;
33 T bottom = fast_power_recursive(a, b >> 1);
34 // Since it is integer division b/2 = (b-1)/2 where b is odd.
35 // Therefore, case2 is easily solved by integer division.
36
37 double result;
38 if ((b & 1) == 0) // case1
39 result = bottom * bottom;
40 else // case2
41 result = bottom * bottom * a;
42 return result;
43}
44
49template <typename T>
50double fast_power_linear(T a, T b) {
51 // negative power. a^b = 1 / (a^-b)
52 if (b < 0)
53 return 1.0 / fast_power_linear(a, -b);
54
55 double result = 1;
56 while (b) {
57 if (b & 1)
58 result = result * a;
59 a = a * a;
60 b = b >> 1;
61 }
62 return result;
63}
64
68int main() {
69 std::srand(std::time(nullptr));
70 std::ios_base::sync_with_stdio(false);
71
72 std::cout << "Testing..." << std::endl;
73 for (int i = 0; i < 20; i++) {
74 int a = std::rand() % 20 - 10;
75 int b = std::rand() % 20 - 10;
76 std::cout << std::endl << "Calculating " << a << "^" << b << std::endl;
77 assert(fast_power_recursive(a, b) == std::pow(a, b));
78 assert(fast_power_linear(a, b) == std::pow(a, b));
79
80 std::cout << "------ " << a << "^" << b << " = "
81 << fast_power_recursive(a, b) << std::endl;
82 }
83
84 int64_t a, b;
85 std::cin >> a >> b;
86
87 std::cout << a << "^" << b << " = " << fast_power_recursive(a, b)
88 << std::endl;
89
90 std::cout << a << "^" << b << " = " << fast_power_linear(a, b) << std::endl;
91
92 return 0;
93}
double fast_power_linear(T a, T b)
double fast_power_recursive(T a, T b)
int main()