// header
line: long return value since factorials grow
rapidly!
{
if (n == 1) // this
tests to see if nis 1, the base case
return
1; // if so, the function returns 1
return
n*factorial(n-1); // assumes n >= 1
//
otherwise a recursive call – factorial calls itself!
// this second
returnexecutes if the ifcondition is
false
}
Your job for this part of the Lab is to create and testa similar
recursive function that calculates and returns an integer
power pof some integer number
n; nand
pare the parameters to the function, with
header line staticlong power(int n, int
p). You can assume that pis at
least 0.Modify the above factorial function as follows:
Update the headerline for the function as above and then make these
changes:
The base caseforthe
powerfunction occurs when pis
0, at which point the function returns the value
1(by definition, any number raised to the 0 power
is 1). To test for 0, the base case, replace the
ifcondition with this one: if (p ==
0).
If pis not0
then the function should return
n*power(n,
p-1)ànpisn•n(p-1)
if pis greater than 0. Use that
information to change the second
returnstatement.
Now test to make sure
powerworks by having
maincall it with some known values and
print out the results. For example, power(3, 2)
should return
32=9,
power(-2, 7) should return
(-2)7=-128, and
power(8, 0) should return 1.
Derive Power.java from Factorial.java, and modify mainto test power.
If you have any doubts, please give me comment...
public class Power {
public static long power(int n, int p) {
if (p == 0)
return 1;
else
return n * power(n, p - 1);
}
public static void main(String[] args) {
System.out.println("power(3,2) = "+power(3, 2));
System.out.println("power(-2,7) = "+power(-2, 7));
System.out.println("power(8,0) = "+power(8, 0));
}
}
Get Answers For Free
Most questions answered within 1 hours.