简体   繁体   English

算法分析

[英]Algorithm Analysis

I have an algorithm with the following pseudocode: 我有一个带有以下伪代码的算法:

R(n)
if(n = 1)
  return 1
else
  return(R(n-1) + 2 * n + 1)

I need to setup a recurrence relation for the number of multiplications carried out by this algorithm and solve it. 我需要为该算法执行的乘法次数设置一个递归关系,并将其求解。

Is the following right? 以下是对的吗?

R(1) = 0
R(n) = R(n-1) + n^2

You are performing only one multiplication per step. 每步只执行一次乘法。 Therefore, the relation will be: 因此,该关系为:

R(n) = R(n-1) + 1

In the algorithm as shown, R(n) is calculated by adding R(n-1) to 2*n+1. 在所示的算法中,通过将R(n-1)与2 * n + 1相加来计算R(n)。 If 2*n is calculated using a multiplication, there will be one multiplication per level of recursion, thus n-1 multiplications in the calculation of R(n). 如果使用乘法计算2 * n,则每个递归级别将有一个乘法,因此R(n)的计算中将有n-1个乘法。

To compute that via a recurrence, let M(n) be the number of multiplications used to compute R(n). 为了通过递归来计算,令M(n)为用于计算R(n)的乘法数。 The recurrence boundary condition is M(1) = 0 and the recurrence relation is M(i) = M(i-1) + 1 for i>1. 对于i> 1,递归边界条件为M(1)= 0,递归关系为M(i)= M(i-1)+ 1。

Errors in writing “R(1) = 0; 写入“ R(1)= 0; R(n) = R(n-1) + n^2” as the recurrence for the number of multiplications include: R(n)= R(n-1)+ n ^ 2”,因为乘法的重复次数包括:
• R() already is in use as a function being computed, hence re-using R() as the number of multiplications is incorrect •R()已被用作要计算的函数,因此由于乘法次数不正确,因此重新使用R()
• Each level of recursion in the algorithm adds one multiplication, not n² multiplications. •算法中的每个递归级别都添加一个乘法,而不是n²乘法。

Note, R(n) = 1 + 5 + 7 + ... + 2n+1 = 1 + 3 + 5 + 7 + ... + 2n+1 - 3 = n²-3; 注意,R(n)= 1 + 5 + 7 + ... + 2n + 1 = 1 + 3 + 5 + 7 + ... + 2n + 1-3 =n²-3; that is, function R(n) returns the value n²-3. 也就是说,函数R(n)返回值n²-3。

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

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