Suppose we have A 1 = 4 and A n = 3( A n %u2212 1 ) %u2212 5 . That is, we want
ID: 3538939 • Letter: S
Question
Suppose we have
A1 = 4
and
An = 3(An%u22121) %u2212 5.
That is, we want to compute the nth value in the sequence starting 4, 7, 16, 43,
124, ... Implement the following method recursively
This method will calculate and return the nth value in the sequence An. Your base case is when n = 1. When n = 1, the method returns 4. In the recursive case, you will use the method anth(...) to calculate An%u22121, then return five less this value multiplied by three. A non-recursive implementation of this method will not receive credit.
For the second method, recall that ("somestring").substring(1) yeilds "omestring". In other words, given a string, substring(1) applied to that string returns everything but the first character of the string. Also note that ("").substring(1) throws an exception %u2013 do not use substring(1) on empty strings. Recall also that ("somestring").charAt(0) is the first character of a string (in this case, it is %u2019s%u2019. Like substring(1), charAt(0) will not work on empty strings (it throws an exception in this case). Using substring(1) and charAt(1) write a recursive method with the following header that reverses the string it is given:
The result of reverse("somestring") is "gnirtsemos". The result of reverse("a") is "a". Since the reversal of an empty string ("") is the same string (""), the empty string is a good base case. In all other cases, the length of the string must be at least 1. If the length of the string is at least 1, we can take the remainder of the string (everything but the first character), reverse it, append
the first character on the end and return the result. To reverse the remainder of the string, use a recursive call to reverse. Non-recursive implementations of this method will not receive any credit.
Put both these methods in a class called Recursion2.java.
Explanation / Answer
class Recursion2
{
public static int anth(int n)
{
if(n==1)
return 4;
//recursively call if n>1,just as relaton An=3*A(n-1) -5
return ((3*anth(n-1))-5);
}
public static String reverse(String s)
{
if(s.length()==0)
return "";
//recursively append first character at the end of the reverse of remaining string
return (reverse(s.substring(1))+s.charAt(0));
}
}