I'm trying to learn recursion. I've been trying to write the Recamans sequence with a recursive function.
#include <stdio.h>
int recursion(int inputnum){
if (inputnum==0){
printf("term %d, zero returned\n",inputnum);
return 0;
}
else {
if ((recursion(inputnum-1)-inputnum)<0){
printf("returning %d at term %d \n",(recursion(inputnum-1)+ inputnum),inputnum);
return (recursion(inputnum-1)+inputnum);
}
else {
printf("returning %d at term %d \n",(recursion(inputnum-1)- inputnum),inputnum);
return (recursion(inputnum-1)-inputnum);
}
}
}
int main(void){
int numberofterms;
numberofterms=3;
printf("%d",recursion(numberofterms));
}
As far as I know, I know I need to set a base case for the function which will return the simplest value for the problem, and in the case of my program, the variable inputnum should be increasing after it reaches 0. However, the debugging statement I put {printf("term %d, zero returned\n",inputnum);}
still keeps showing up after the inputnum value seems to have gone up. Would anyone kindly point out the problems in this program?
Recamán's sequence does indeed go up and down. Your debugging output, besides being wrong initially, is confusing to you because you have 3 recursive calls for inputnum > 0
. Instead you want to calculate recursive(inputnum-1)
once and assign it to a temporary variable.
#include <stdio.h>
#define N 6
int recursion(int n) {
if (n == 0) return 0;
int tmp = recursion(n-1);
if (tmp - n > 0) return tmp - n; // TODO: "and not already in the sequence"
return tmp + n;
}
int main() {
for(int i = 0; i < N; i++)
printf("%d%s", recursion(i), i + 1 < N ? ", " : "\n");
}
and here is sample output:
0, 1, 3, 6, 2, 7
The next step is to use dynamic programming (DP) to store the sequence into an array so you can use those partial results instead calculate the same thing over and over. This will also allow you to address the TODO in the above.