-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP4_7.java
More file actions
46 lines (41 loc) · 955 Bytes
/
P4_7.java
File metadata and controls
46 lines (41 loc) · 955 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
public class P4_7
{
public static void main(String[] args) {
System.out.println(pow(2, 12));
System.out.println(pow(2,5));
}
//Write a function that returns x to the power of y.
//pow(3,2) = 9;
//Assume y is non-negative
public static double pow(double x, int y)
{
double result = 1.0;
int power = y;
while(power != 0)
{
if((power & 1) != 0)
{
result *= x;
}
x *= x;
power >>>=1;
}
return result;
}
public static double powRecursive(double x, int n)
{
if(n == 0)
return 1;
double temp = pow(x, n /2);
if(n % 2 == 0)
{
return temp * temp;
}else
{
if(n > 0)
return x * temp * temp;
else
return (temp * temp)/x;
}
}
}