This problem begs for contorted solutions.
Here is one that uses a single function taking one or two int
arguments:
- if the first argument is positive, it computes the expression for that value
- if the first argument is negative, it must be followed by a second argument and performs a single step in the computation, recursing for the previous step.
- it uses
<stdarg.h>
which might or might not be allowed.
Here is the code:
#include <math.h>
#include <stdarg.h>
double rec_sqrt_series(int n, ...) {
if (n < 0) {
va_arg ap;
va_start(ap, n);
int m = va_arg(ap, int);
va_end(ap);
if (m > -n) {
return 0.0;
} else {
return sqrt(m + rec_sqrt_series(n, m + 1));
}
} else {
return rec_sqrt_series(-n, 1);
}
}
Here is another solution with a single function, using only <math.h>
, but abusing the rules in a different way: using a macro.
#include <math.h>
#define rec_sqrt_series(n) (rec_sqrt_series)(n, 1)
double (rec_sqrt_series)(int n, int m) {
if (m > n) {
return 0.0;
} else {
return sqrt(m + (rec_sqrt_series)(n, m + 1));
}
}
Yet another one, strictly speaking recursive, but with single recursion level and no other tricks. As Eric commented, it uses a for
loop which might be invalid under the OP's constraints:
double rec_sqrt_series(int n) {
if (n > 0) {
return rec_sqrt_series(-n);
} else {
double x = 0.0;
for (int i = -n; i > 0; i--) {
x = sqrt(i + x);
}
return x;
}
}
helper
? – Grummetabort()
(from<stdlib.h>
), not silently return 0. – Redhot<stdio.h>
andprintf
to test your code, right? – Redhotdouble nested_root(unsigned n) { double x = 0.0; if (n > 0) { x = nested_root(0); for (unsigned i = n; i > 0; i--) { x = sqrt(i + x); } } return x; }
– Lowestoft