C++ 中 Kn + ( K(n-1) * (K-1)1 ) + ( K(n-2) * (K-1)2 ) + ... (K-1)n 系列的和
在这个问题中,我们得到了该系列的两个数字 k 和 n:K^n + ( K^(n-1) * (K-1)^1 ) + ( K^(n-2) * (K-1)^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
广告