forked from natural/java2python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpower.java
More file actions
32 lines (32 loc) · 659 Bytes
/
power.java
File metadata and controls
32 lines (32 loc) · 659 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
public class Power
{
public static void main (String[] args)
{
System.out.println (power(1, 1024));
}
static double power (double x, int n)
{
if (n == 0)
{
return 1.0;
}
else if (n > 0)
{
if (n % 2 == 0)
{
int p = (int)power(x, n/2);
//(x^(n/2))^2 = x^(n/2) * x^(n/2)
return p * p;
}
else
{
//x^n = x*x^(n-1)
return x * power(x, n-1);
}
}
else
{
return 1.0 / power(x, -n);
}
}
}