-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPow.java
More file actions
55 lines (47 loc) · 727 Bytes
/
Pow.java
File metadata and controls
55 lines (47 loc) · 727 Bytes
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
public class Pow {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public double pow(double x, int n) {
if(n==0) return 1.0;
if(x == 1.0) return 1.0;
if(x == -1.0)
{
if(n%2==0)
{
return 1.0;
}
else
{
return -1.0;
}
}
boolean isNegtaive = (n < 0);
n = Math.abs(n);
double x0 = x;
double x1 = 1;
while(n!=1)
{
if(n%2 == 0)
{
x0 *=x0;
}
else
{
x1 *=x0;
x0 *=x0;
}
n = n/2;
}
if(isNegtaive)
{
return 1/x0/x1;
}
else{
return x0*x1;
}
}
}