快速幂对于计算整数的幂特别有用。而 pow() 可以计算浮点数幂。
直接上代码
#include <iostream>
#include <chrono>
#include <cmath>
using namespace std;
long long fastExponentiation(long long base, long long exponent) {
if (exponent == 0) {
return 1;
}
long long result = 1;
while (exponent > 0) {
if (exponent % 2 == 1) {
result *= base;
}
base *= base;
exponent /= 2;
}
return result;
}
int main() {
long long base = 2;
long long exponent = 30;
long long result1;
double result2;
auto start_time1 = chrono::high_resolution_clock::now();
for (int i = 0; i < 1000000; i++) {
result1 = fastExponentiation(base, exponent);
}
auto end_time1 = chrono::high_resolution_clock::now();
chrono::duration<double> elapsed_time1 = end_time1 - start_time1;
auto start_time2 = chrono::high_resolution_clock::now();
for (int i = 0; i < 1000000; i++) {
result2 = pow(base, exponent);
}
auto end_time2 = chrono::high_resolution_clock::now();
chrono::duration<double> elapsed_time2 = end_time2 - start_time2;
cout << "Fast Exponentiation: " << result1 << endl;
cout << "Time taken for fast exponentiation: " << elapsed_time1.count() << " seconds" << endl;
cout << "pow function: " << result2 << endl;
cout << "Time taken for pow function: " << elapsed_time2.count() << " seconds" << endl;
return 0;
}
输出结果:
Fast Exponentiation: 1073741824
Time taken for fast exponentiation: 0.0127223 seconds
pow function: 1.07374e+09
Time taken for pow function: 0.0454114 seconds