I was given an assignment a few months ago that had a handful of random components. One was a recursive function that had a lot of fluff to it but shouldn't have been too hard. However, I couldn't figure out how to write it. I've gone back to it and I still can't quite figure it out. You can see the full assignment here if you'd like: http://www.cs.fsu.edu/~asriniva/courses/DS14/projs/proj2.html
I'm only dealing with the section called main.cpp: This is a program to evaluate a recursive function. It has nothing to do with the previous part of the assignment. The command: ./recurse N1 C1 A1 M1 M2 M3 M4 D1 D2 S1 S2 Arg Op will cause the function given below to be evaluated recursively and the answer output. The function is defined as follows.
f(N) = 0, if N < N1
f(N1) = C1
f(N)= A1 + M1*f(M2*N/D1 - S1) Op M3*f(M4*N/D2 - S2), if N > N1
Here, f(Arg) needs to be evaluated. N1 C1 A1 M1 M2 M3 M4 D1 D2 S1 S2, Arg are integers and Op is either + or -. The division performed is the usual integer division with truncation.
I got a semi working program but, first, it uses some global variable, second, I get a warning "recurse.cpp:37: warning: control reaches end of non-void function", and, most importantly, it doesn't actually work. I gives a result that is incorrect but its better than my original attempt that couldn't actually give a result. Please help me understand how to get this thing working, I've spent more time than I'd like trying to by myself.
This is supposed to run on a unix machine with an executable call followed by command line arguments. Like so: Prompt> ./recurse 2 3 2 1 2 0 1 3 6 0 0 18 +
13 (program output)
#include <iostream>
#include <cstdlib>
using namespace std;
char * Op;
int N1;
int C1;
int A1;
int M1;
int M2;
int M3;
int M4;
int D1;
int D2;
int S1;
int S2;
int recurse(int N){
if (N < N1){
return 0;
}
if (N == N1){
return C1;
}
if (N > N1){
if (*Op == '+')
return (A1 + M1 * recurse((M2*N / D1 - S1)) + M3 *
recurse((M4*N / D2 - S2)));
else
return (A1 + M1 * recurse((M2*N / D1 - S1)) - M3 *
recurse((M4*N / D2 - S2)));
}
}
int main(int argc, char* argv[]){
N1 = atoi(argv[1]);
C1 = atoi(argv[2]);
A1 = atoi(argv[3]);
M1 = atoi(argv[4]);
M2 = atoi(argv[5]);
M3 = atoi(argv[6]);
M4 = atoi(argv[7]);
D1 = atoi(argv[8]);
D2 = atoi(argv[9]);
S1 = atoi(argv[10]);
S2 = atoi(argv[11]);
Op = argv[12];
int val;
if (*Op == '+')
val = ( ( A1 + M1 * recurse(M2 / D1 - S1) + M3 *
recurse(M4 / D2 - S2) ) );
else
val = ( ( A1 + M1 * recurse(M2 / D1 - S1) - M3 *
recurse(M4 / D2 - S2) ) );
cout << val << endl;
return 0;
}
Thanks for the help!