Question: Programming Language: JAVA Question 4: The factorial of n, or n!, is defined as the series of products 1 2 ... n . Write a
Programming Language: JAVA
Question 4: The factorial of n, or n!, is defined as the series of products 1 2 ... n. Write a recursive method and an iterative method that each compute n!. Verify that both methods return the same result for any given positive value of n. Then, execute both methods for larger and larger values of n. What is the largest value of n that will successfully produce a result for each method?
Question 5: What is the output of the following program? public class Exercise5 { public static void main(String[] args) { System.out.println("Sum = " + guessResult(4)); } // end main public static int guessResult(int n) { boolean result; if (n == 1) { result = 1; } else { result = n + guessResult(n - 1); } return result; } // end guessOutput } // end Exercise5
Question 8: Identify and fix the errors in the following program: public class Exercise8 { public static void main(String[] args) { Exercise8 ex = new Exercise8(); System.out.println(ex); } // end main public Exercise8() { Exercise8 ex = new Exercise8(); } // end default Exercise8 constructor } // end Exercise8
Question 14: Write a recursive method that displays a given message n times.
Question 15: Define a recursive method f that, given a nonnegative integer n, returns n % 2 when n ranges from 0 to 9 f(n / 10) + (n % 10) % 2 when n is greater than or equal to 10
Question 16: Jack and Jill take turns using a one-gallon pail to empty a tank of water. On his turn, Jack always removes one gallon of water. Jill, however, removes one or two gallons so that either an even number of gallons are left in the tank or the tank becomes empty. Using recursion, how many turns in total must Jack and Jill make to empty the tank, if it initially contains n gallons? Write a recursive method that counts and returns the total number of turns given the number of gallons n.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
