Write a recursive definition for the following methods and test the methods 1. C
ID: 3572996 • Letter: W
Question
Write a recursive definition for the following methods and test the methods
1. Compute the product of n integers
productInteger(n) = 1*2*3*4*5*…*n (n >=1)
• Test it with productInteger(4)
2. Compute the product of n even integers
productEven(n) = 2*4*6*8*10*…*[2*(n-1)]*[2*n] (n >=1)
• Test it with productEven(5)
3. Compute the product of n odd integers
productOdd(n) = 1*3*5*7*9*...*[2*(n-1) - 1]*[2*n -1] (n >=1)
• Test it with productOdd(6)
Using standard java code for the fundamental programming class.
Explanation / Answer
ProductTest.java
public class ProductTest {
public static void main(String[] args) {
System.out.println(productInteger(4));
System.out.println(productEven(5));
System.out.println(productOdd(6));
}
public static int productInteger(int n){
if(n == 1){
return 1;
}
else{
return n * productInteger(n-1);
}
}
public static int productEven(int n){
if(n == 1){
return 2;
}
else{
return (2 * n) * productEven(n-1);
}
}
public static int productOdd(int n){
if(n == 1){
return 1;
}
else{
return (2 * n - 1) * productOdd(n-1);
}
}
}
Output:
24
3840
10395
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.