Do not use static variables to implement recursive methods. Problem 1 You have b
ID: 3793853 • Letter: D
Question
Do not use static variables to implement recursive methods.
Problem 1
You have been offered a job that pays as follows:
On the first day, you are paid 1 cent, on the second day, 2 cents, on the third day, 4 cents and so on. In other words, your pay doubles every day. Write a recursive method computePay that for a given day number computes the pay in cents.
Assume that you accumulate all the money that you are paid. Write a recursive method computeSavingsthat computes the sum that you have accumulated on a given day. Show the output of computePay andcomputeSavings for day number 39.
Problem 2
Write a recursive method countSubstrings that counts the number of non-overlapping occurrences of a string s2 in a string s1. Use the method indexOf() from String class.
As an example, with s1=”abab” and s2=”ab”, countSubstrings returns 2. With s1=”aaabbaa” and s2=”aa”, countSubstrings returns 2. With s1=”aabbaa” and s2=”AA”, countSubStrings returns 0.
Show the output on the following strings:
s1 = “Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible. Java is currently one of the most popular programming languages in use, particularly for client-server web applications, with a reported 10 million users.”
s2= “Java”.
Explanation / Answer
Hi, I have implemented Q1.
Please let me know in case of any issue.
public class ComputePayProg {
// Helper function of computePay
public static long computePayUtil(int day, long pay){
// Base case
if(day == 1)
return pay;
return computePayUtil(day-1, pay*2);
}
public static long computePay(int day){
return computePayUtil(day, 1);
}
public static long computeSavings(int day){
return computeSavingsUtil(day, 1);
}
public static long computeSavingsUtil(int day, long pay){
// Base case
if(day == 1)
return 1;
pay = pay*2;
return pay + computeSavingsUtil(day-1, pay);
}
public static void main(String[] args) {
System.out.println("Pay on 39th day: "+computePay(39));
System.out.println("Total pay for 39 days: "+computeSavings(39));
}
}
/*
Sample run:
Pay on 39th day: 274877906944
Total pay for 39 days: 549755813887
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.