在问题中,我们是序列K ^ n +(K ^(n-1)*(K-1)^ 1)+(K ^(n-2)*(K-1)的两个数字k和n )^ 2)+ ...(K-1)^ n。我们的任务是创建一个程序来查找序列的总和。
Input: n = 3, k = 4 Output: 175 Explanation: Sum of the series is = 4^3 + ( (4^2)*(3^1) ) + ( (4^1)*(3^2) ) + ( (4^0)*(3^3) ) = 64 + 48 + 36 + 27 = 175
解决问题的一种简单方法是使用for循环。找到该系列的每个术语,并将其值加到总和上。
initialise sum = 0; Step 1: for i -> 0 to n. Step 1.1: update sum: sum += pow(k, n-i) * pow(k, i) Step 2: return sum.
该程序说明了我们解决方案的工作原理,
#include <iostream> #include <math.h> using namespace std; int calcSeriesSum(int k, int n) { int sum = 0; for (int i = 0; i <= n; i++) { int p = pow(k, n-i) * pow((k-1), i); sum = sum + p; } return sum; } int main() { int n = 4; int K = 2; cout<<"Sum of the series is "<<calcSeriesSum(K, n); }
输出结果
Sum of the series is 31
该解决方案效率不高,并且花费的时间约为n。
一个有效的解决方案是找到级数总和的通用公式。
The series K^n + ( K^(n-1) * (K-1)^1 ) + ( K^(n-2) * (K-1)^2 ) + ... (K-1)^n Forms a geometric progression. The common ration of this progression is (k-1)/k and the first term is k^n. sum = K^n + ( K^(n-1) * (K-1)^1 ) + ( K^(n-2) * (K-1)^2 ) + ... (K-1)^n sum = kn(1 + (k-1)/k + (k-1)2/k2 + … + (k-1)n) sum = ((kn)(1 - ( (k-1)(n+1))/k(n+1))) / (1 - ((k-1)/k)) sum = kn ( (k(n+1) - (k-1)(n+1))/k(n+1) ) / ( (k - (k-1))/k ) sum = kn ( (k(n+1) - (k-1)(n+1))/k(n+1) ) / (1/k) sum = kn ( (k(n+1) - (k-1)(n+1))/k(n+1) ) * k sum = ( k(n+1) - (k-1)(n+1) )
该程序说明了我们解决方案的工作原理,
#include <iostream> #include <math.h> using namespace std; int calcSeriesSum(int k, int n) { return ( pow(k,(n+1)) - pow((k-1),(n+1)) ); ; } int main() { int n = 4; int K = 2; cout<<"Sum of the series is "<<calcSeriesSum(K, n); }
输出结果
Sum of the series is 31