[英]How to calculate value of the recursive function?
I have the recursive function: T(n) = 2T(n/2) + n. 我有递归函数:T(n)= 2T(n / 2)+ n。 I want to find the complexity of the function by passing different arguments to the function and getting values of the function.
我想通过将不同的参数传递给函数并获取函数的值来发现函数的复杂性。 Then I will guess the formula of the function(eg n, n*log(n)).
然后,我将猜测函数的公式(例如n,n * log(n))。
I write the following code: 我编写以下代码:
public static void main(String[] args) {
System.out.println(findValueOfTheFunction(2));
System.out.println(findValueOfTheFunction(4));
System.out.println(findValueOfTheFunction(8));
}
static double findValueOfTheFunction(double n) {
if(n > eps) {
return 2*findValueOfTheFunction(n/2) + n;
}
else return 0;
}}
I get three points from the code. 我从代码中得到了三点。 p1(2, 10) and p2(4, 24) and p3(8, 56).
p1(2,10)和p2(4,24)和p3(8,56)。
As a understand, the complexity of the recursive function is O(n) = n*log(n). 可以理解,递归函数的复杂度为O(n)= n * log(n)。 But my points doesn't fit to the formula.
但是我的观点与公式不符。
I've done some research here, but nobody seems to have similar issue. 我在这里做了一些研究,但似乎没有人遇到类似的问题。
Your very first problem is here: 您的第一个问题在这里:
else return 0;
At some point; 在某一点; your recursion ends;
您的递归结束; and reaches that if.
并达到,如果。
And then you start multiplying the result of that last call ... and guess what x * y * z * ... * 0 might compute to?! 然后,您开始乘以最后一个调用的结果...,然后猜测x * y * z * ... * 0可能计算得出的值?
So all your method is doing is returning some m * n value (where n is your input; and m depends on how often you recursively call your own method. As your code translates to: 因此,您的方法所做的就是返回一些m * n值(其中n是您的输入;而m取决于您递归调用自己的方法的频率。代码转换为:
if (n>eps) {
return n + findValueOfTheFunction(n/2)
Long story short: your computation looses the "interesting" part of its result. 长话短说:您的计算失去了结果的“有趣”部分。 So - instead of returning 0 ... return 1!
所以-而不是返回0 ...返回1!
Do you have to write code for this? 您是否需要为此编写代码? You can do some math by giving values to n and then substitution:
您可以通过给n赋值然后进行替换来做一些数学运算:
t(1) = 2t(1/2) + 1
t(2) = 2t(1) + 1 = 2(2t(1/2)+1) = 2*2t(1/2)
t(4) = 2t(2) + 1 = 2*2*2*t(1/2)
t(8) = 2t(4) + 1 = 2*2*2*2*t(1/2)
The remaining 2*1 is not so important, you can keep staying with t(1/2) part. 剩下的2 * 1不是那么重要,您可以继续使用t(1/2)部分。 I guess already something is coming up.
我想已经有事情发生了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.