-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path11_Power.cpp
More file actions
82 lines (73 loc) · 1.69 KB
/
11_Power.cpp
File metadata and controls
82 lines (73 loc) · 1.69 KB
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
#include <iostream>
#include <iomanip>
using namespace std;
bool g_InvalidInput = false;
bool equal(double num1, double num2)
{
if ((num1 - num2 > -0.0000001) && (num1 - num2 < 0.0000001))
return true;
else
return false;
}
double PowerWithUnsignedExponent(double base, unsigned int absexponent)
{
double result = 1.0;
/* this solution is not good enough. O(n)
int i = 0;
for (i = 0; i < absexponent; i ++)
result = result * base;
return result;
*/
// O(lgn)
if (absexponent == 0)
return 1.0;
if (absexponent == 1)
return base;
result = PowerWithUnsignedExponent(base, absexponent >> 1);
result *= result;
if ((absexponent & 0x1) == 1)
result = base * result;
return result;
}
double Power(double base, int exponent)
{
g_InvalidInput = false;
if (equal(base, 0.0) && exponent < 0)
{
g_InvalidInput = true;
return 0.0;
}
unsigned int absExponent;
if (exponent < 0)
absExponent = (unsigned int)(-exponent);
else
absExponent = (unsigned int)exponent;
double result = PowerWithUnsignedExponent(base, absExponent);
if (exponent < 0)
result = 1.0 / result;
return result;
}
int main()
{
int T, exponent;
double base, result;
cin >> T;
while (T--)
{
cin >> base;
cin >> exponent;
result = Power(base, exponent);
if (g_InvalidInput == 1)
cout << "INF" << endl;
else
{
//g++ doesn't use this format, there is two digits of the exponent.
// while in VS, there is 3, so we have to set this.
// according to the requests, exponent have to be two digits
unsigned int format = _set_output_format(_TWO_DIGIT_EXPONENT);
//printf("%.2e\n", result);
cout << setiosflags(ios::scientific) << setprecision(2) << result << "f" << endl;
}
}
return 0;
}