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 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
#include <iostream>
using namespace std;
template <class T>
T power1(T x, unsigned int n, unsigned int& mults);
template <class T>
T power2(T x, unsigned int n, unsigned int& mults);
template <class T>
T power3(T x, unsigned int n, unsigned int& mults);
template <class T>
void printReport(T base, unsigned int pow,
T result1, T result2, T result3,
unsigned int mults1, unsigned int mults2,
unsigned int mults3);
int main()
{
unsigned int mults1, mults2, mults3;
cout << "Test for integer base:\n";
for (unsigned int pow = 0; pow <= 32; pow++) {
unsigned int base = 2;
unsigned int result1 = power1(base, pow, mults1);
unsigned int result2 = power2(base, pow, mults2);
unsigned int result3 = power3(base, pow, mults3);
printReport(base, pow, result1, result2, result3,
mults1, mults2, mults3);
}
cout << "\nTest for floating-point base:\n";
for (unsigned int pow = 0; pow <= 64; pow++) {
double base = 0.5;
double result1 = power1(base, pow, mults1);
double result2 = power2(base, pow, mults2);
double result3 = power3(base, pow, mults3);
printReport(base, pow, result1, result2, result3,
mults1, mults2, mults3);
}
}
template <class T>
T power1(T x, unsigned int n, unsigned int& mults)
{
mults = 0;
unsigned int temp;
if (n == 0) return 1;
if (n == 1) return x;
else {
for (temp = x; n > 1; n--){
temp *= x;
mults++;
}
return temp;
}
return 1;
}
template <class T>
T power2(T x, unsigned int n, unsigned int& mults)
{
if (n == 0) return 1;
if (n == 1) return x;
else if (n > 1){
mults++;
return x * power2(x, n - 1, mults);
}
return 0;
}
template <class T>
T power3(T x, unsigned int n, unsigned int& mults)
{
if (n == 0) return 1;
if (n == 1) return x;
if (n == 2){
mults++;
return x * x;
}
if (n%2 == 0){
mults++;
return power3((power3(x,(n/2),mults)),2,mults);
}
else if(n%2 != 0){
mults++;
return x * power3((power3(x,((n-1)/2),mults)),2,mults);
}
return 0;
}
template <class T>
void printReport(T base, unsigned int pow,
T result1, T result2, T result3,
unsigned int mults1, unsigned int mults2,
unsigned int mults3)
{
cout << base << "^" << pow << " = ";
if (result1 == result2 && result2 == result3)
cout << result1 << ": ";
else
cout << "(" << result1 << ", " << result2 << ", " << result3
<< ") [ERROR!]: ";
cout << "mults1 = " << mults1 << ", mults2 = " << mults2
<< ", mults3 = " << mults3 << endl;
}
|