I was recently given a project as follows:
Recursive relationship : x(n) = x(n+1) - 2x(n-1) where x(0) = 1 and x(2) = 3 Write a program where the user enters a number, n, and the nth value of x, as shown above is output.
so far, I have made this method ( I am very new to, and really bad with [so far] recursion)
public class x
{
static int x(int n)
{
if(n <= 1)
{
return 1;
}
if(n == 2)
{
return 3;
}
else
{
return x(n+1) - 2*(x(n-1));
}
}
and a simple main method that prompts the user for an input of n, and then prints the result of the above method:
public static void main(String[]args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = scanner.nextInt();
System.out.println(x(n));
}
From the assignment, I calculated that x(1) = 1. [Being I am given x(0) = 1 and x(2) = 3]:
x(n) = x(n+1) - 2(x(n-1))
x(1) = x(2) - 2(x(0))
x(1) = 3 - 2(1)
x(1) = 3 - 2
x(1) = 1
which brought me to my base case shown in the static method x above,
if(n <= 1) // because 0 and 1 each return 1
{
return 1;
}
if(n == 2) // simply because 2 returns 3
{
return 3;
}
When I run what I have, the program gives me the error :
Exception in thread "main" java.lang.StackOverflowError
at x.x(x.java:21)
Java Result: 1
Line 21 is the return statement in the else clause of the x method:
return x(n+1) - 2*(x(n-1));
and I have no idea what I can change to fix it. I have tried restating it as x(n+1)-x(n-1)-x(n-1), but it continues to give me the same error. I don't know if it is the base case being invalid and therefore not allowing the function to run it's course properly, or just the return statement I made is wrong. I also tried writing it out as if x(5) calls x(4) calls x(3), so on as my notes show, but I arrive at an issue regarding having n+1 and n-1 in the same function statement, so I think I am just going about it the wrong way. Any guidance on this is extremely appreciated!
Issue is because it is never ending loop.... x(n) = x(n+1) - 2x(n-1)
You are incrementing n,ie, for
x(0) = 1
x(1) = x(2) - 2 x(0)
x(3) = x(4) - 2 x(2)....
It keeps on going as there is no upper limit for x(n+1)....
Please check if you are not missing boundary condition for it from where recursion will terminate.
Recurrence relation is defined as a function of the preceding terms. So you have to redefine your recursive relationship as,
x(n) = x(n+1) - 2x(n-1)
x(n+1) = x(n) + 2x(n-1)
x(n) = x(n - 1) + 2x(n-2)
Use above equation to implement the algorithm with base cases x(0) = x(1) = 1, x(2) = 3
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.