The series, , is an arithmetic series,and The series, , is a geometric series。
本文主要分析三种计算Geometric series summation的算法,应用的是简化模型。
1,直接法(点击打开链接)
int GeometricSeriesSum(int x, unsigned n)
{
int sum = 0;
for (unsigned int i = 0; i <= n; ++i)
{
int prod = 1;
for (unsigned int j = 0; j < i; ++j)
prod *= x;
sum += prod;
}
return sum;
}
时间开销T(n) = 11/2 * n*n + 47/2 * n + 24
2,应用Honer's Rule()
int GeometricSeriesSum(int x, unsigned n)
{
int sum = 0;
for (unsigned int i = 0; i <= n; ++i)
sum = sum * x + 1;
return sum;
}
时间开销T(n) = 13*n + 22
3,应用递归法求幂,再计算Geometric Series Summation (点击打开链接)
int Power(int x, unsigned int n)该递归求幂算法的时间开销T(n) = 19 * ( [log2(n)] + 1) + 5
{
if (0 == n)
return 1;
else if (! ( n & 1 ) ) // n is even
return Power(x * x, n/2);
else // n is odd
return x * Power(x * x, n/2);
}
再利用等比数列求和公式,如下:
int GeometricSeriesSum(int x, unsigned n)
{
return (Power(x, n+1) - 1 ) / (x - 1)
}
综合时间开销T(n) = 19 * ( [log2(n+1)] + 1) + 18
使用matlab绘制三种算法时间趋势图,如下: