-
Recursive Sequence
I want to input a recursive sequence into a program for the computer to calculate it, but I am having some trouble doing so.
Does anyone have any bright ideas to represent this sequence?
a_n = sqrt(x)
a_n+1 = sqrt(x + a_n)
This is my code...thanks for any input.
Code:
#include <stdio.h>
#include <math.h>
float sequence (float x, int recurse);
int main()
{
float limit;
limit = sequence(3, -20);
printf("%f", limit);
getchar();
return 0;
}
float sequence (float x, int recurse)
{
float answer;
if ( recurse )
{
answer = sqrt(x + sequence(answer, recurse++) );
}
else
return answer;
}
-
For something so simple, consider not even using a recursive function.
:eek:
-
Where's the fun in that, treenef, if he's trying to learn recursion?
If recurse is not negative, your function will run so long that that recursive function will probably cause you problems.
Try to return the value without storing it in a temporary variable. This will save space and make it easier for your compiler to optimize it.
http://en.wikipedia.org/wiki/Tail_recursion