简体   繁体   English

如何解决此乘法算法的递归关系

[英]How to solve the recurrence relation for this Multiplication algorithm

How to I establish a big-O upper bound for the number of times the function calls itself, as a function of b for the following: 我如何确定函数调用自身的次数的big-O上限,作为以下b的函数:

  function multiply(a,b)
     if b = 0 then return 0
     else if b is even then
       t := multiply(a, b/2);
       return t+t;
     else if b is odd then
       t := multiply(a, b-1);
       return a+t;

this is a function to multiply two integer numbers. 这是一个将两个整数相乘的函数。 I'm confused on how to handle the if else conditions for the recurrence relation. 我对如何处理递归关系的if else条件感到困惑。 I was thinking that the answer is T(n) = T(n/2) + T(n-1). 我以为答案是T(n)= T(n / 2)+ T(n-1)。 Is that correct? 那是对的吗?

 function multiply(a,b)
     if b = 0 then return 0
     else if b is even then
       t := multiply(a, b/2);
       return t+t;
     else if b is odd then
       t := multiply(a, b-1);
       return a+t;

Therefore: 因此:

F(0) = 0
If Even: F(N) = F(N/2) + 1 
If Odd-Even: F(N) = F(N-1) + 1 = F((N-1)/2) + 2 <-next number is definitely even

Solving the odd-even-odd-even case(the worst scenario): 解决奇偶双数情况(最坏的情况):

F(N) = F((N-1)/2) + 2 = O(LogN)

Another way to think of the problems is that we know the odd-even-odd-even case has at most twice the depth of even-even-even-even case. 解决问题的另一种方法是,我们知道奇偶奇数情况的深度最多是偶偶偶数情况的两倍。 The even only case has LogN depth, thus odd-even-odd-even case has at most 2*LogN depth. 偶数情况具有LogN深度,因此奇偶奇数情况最多具有2*LogN深度。

Appreciate the following two points: 赞赏以下两点:

  • Calling multiply with an odd input will trigger a call to the same input minus one, which is an even number. 奇数输入调用multiply将触发对相同输入减一(即偶数)的调用。 This will take one additional call to reach an even number. 这将需要再打一个电话才能达到偶数。
  • Calling multiply with an even input will trigger another call with the input halved. 使用偶数输入调用multiply将触发另一个输入减半的调用。 The resulting number will either be even, or odd, qv the above point. 结果数将是上述点的qv的偶数或奇数。

In the worst case scenario, starting with an even input, it would take two calls to halve the input being passed to multiply . 在最坏的情况下,从偶数输入开始,需要两次调用才能将传递给multiply的输入减半。 This behavior is consistent with 2*O(lgN) running time (where lg is the log base 2). 此行为与2*O(lgN)运行时间(其中lg是基于日志的2)一致。 This is the same as just O(lgN) . 这与O(lgN)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM