问题描述
我被要求仅使用递归来计算以下嵌套根表达式.
I was asked to calculate the following nested root expression using recursion only.
我编写了以下有效的代码,但它们允许我们仅使用一个函数和 1 个输入 n
用于此目的,而不是像我使用的 2 个.有人能帮我把这段代码转换成一个可以计算表达式的函数吗?除了 中的函数外,不能使用任何库.
I wrote the code below that works, but they allowed us to use only one function and 1 input n
for the purpose and not 2 like I used.Can someone help me transform this code into one function that will calculate the expression? cant use any library except functions from <math.h>
.
n=10 的输出:1.757932
double rec_sqrt_series(int n, int m) {
if (n <= 0)
return 0;
if (m > n)
return 0;
return sqrt(m + rec_sqrt_series(n, m + 1));
}
double helper(int n) {
return rec_sqrt_series(n, 1);
}
推荐答案
使用 n
的高位作为计数器:
Use the upper bits of n
as a counter:
double rec_sqrt_series(int n)
{
static const int R = 0x10000;
return n/R < n%R ? sqrt(n/R+1 + rec_sqrt_series(n+R)) : 0;
}
当然,当初始 n
是 R
或更大时,它会出现故障.这是一个更复杂的版本,适用于 n
的任何正值.它有效:
Naturally, that malfunctions when the initial n
is R
or greater. Here is a more complicated version that works for any positive value of n
. It works:
- 当
n
为负数时,它的工作方式与上述版本类似,使用高位计数. - 当
n
为正数时,如果小于R
,则用-n
调用自身,对上述函数求值.否则,它会在R-1
否定的情况下调用自己.这会评估函数,就像它是用R-1
调用的一样.这会产生正确的结果,因为在仅仅几十次迭代后,该系列就停止以浮点格式变化——更深的数字的平方根变得如此稀薄,以至于没有任何影响.因此,该函数对于所有n
的值都相同,超过一个小阈值.
- When
n
is negative, it works like the above version, using the upper bits to count. - When
n
is positive, if it is less thanR
, it calls itself with-n
to evaluate the function as above. Otherwise, it calls itself withR-1
negated. This evaluates the function as if it were called withR-1
. This produces the correct result because the series stops changing in the floating-point format after just a few dozen iterations—the square roots of the deeper numbers get so diluted they have no effect. So the function has the same value for alln
over a small threshold.
double rec_sqrt_series(int n)
{
static const int R = 0x100;
return
0 < n ? n < R ? rec_sqrt_series(-n) : rec_sqrt_series(1-R)
: n/R > n%R ? sqrt(-n/R+1 + rec_sqrt_series(n-R)) : 0;
}
这篇关于在 C 中计算嵌套根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!