Reputation: 21
Need help with this problem, I am very bad at recursion. I need to write a method that does this:
The input variable X is an integer between 1 and 50. The function should return as Y the X-th term of a sequence defined recursively by:
f(1) = 1
f(2) = 3
f(X) = 2*f(X-1) – 2*f(X-2) for X = 3,4,5,...
Your function code should use recursion (not a loop)
TBH I dont even know where to get started. Any help would be appreciated. Here is my current code:
package p1parta;
import java.util.Scanner;
public class RecursiveSeq
{
public static void main(String args[])
{
System.out.println("Please enter a number:");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
System.out.println(sequence(x));
}
public static int sequence(int x)
{
if(x == 1){
return 1;
}
if (x == 2){
return 3;
}
return 2 * sequence(x - 1) - 2 * sequence(x - 2);
}
}
I tried to implement the solution shown but the output I get from the program do not match what I am calculating by hand. In fact just testing inputs 3,4,5,and 6 The only one that matches is 5
Upvotes: 0
Views: 460
Reputation: 27946
Your problem is a perfect use case for recursion. In general the recursive pattern is:
func(context)
if simple case
return simple answer
else
call func(simpler context)
and return combined results
Have a go at implementing using this pattern and come back if you have issues.
Upvotes: 2