级数 5+55+555+... 的前 n 项和
5, 55, 555, ... 是一个可以从等比数列推导出的数列,因此可以使用等比数列公式进行计算。
等比数列是一种数列,其中每一项都是前一项乘以某个特定项(比率)的结果。我们将利用等比数列的知识来求出给定数列的和。
问题陈述
给定一个数字 n,求数列 5+55+555+... 的前 n 项和。
示例
Input − N = 3 Output − 595
解释
5 + 5 + 555 = 595.
Input − N = 5 Output − 61716
解释
5 + 5 + 5 + 5 + 5 = 61716.
解决方案
Let sum = 5 + 55 + 555 +… n terms. This is not GP, but we can relate it to GP in the following manner: = 5(1) + 5(11) + 5(111) + … n terms Taking 5 common: = 5[1 + 11 + 111 + …n terms] Divide and multiply by 9: = 5/9[9 + 99 + 999 + … n terms] = 5/9[(10 – 1) + (100 – 1) + (1000 – 1) + … n terms] = 5/9[(10^1 – 1) + (10^2 – 1) + (10^3 – 1) + … n terms] = 5/9[10^1 + 10^2 + 10^3 ...n terms – (1 + 1 + … n times)] = 5/9[10^1 + 10^2 + 10^3 ...n terms – n] We will solve (10^1 + 10^2 + 10^3 ...n terms) as following: We can observe that it is a GP, where the first term a = 10. And the common ratio r = 10^2/10 = 10. Hence, the GP formula: Sum of n terms = a(r^n-1) / (r-1) (where r>1) Putting the values of r and a: 10^1 + 10^2 + 10^3 ...n terms = 10(10^n-1)/(10-1) Substituting the values: 5/9[10^1 + 10^2 + 10^3 ...n terms – n] = 5/9[10(10n-1)/(10-1) – n] = 50/81(10n – 1) – 5n/9
我们可以使用上述公式来编写解决方案的程序。
伪代码
main()
将 n 初始化为 5。
函数调用:sumOfSeries(n)
sumOfSeries(int n)
product = 0.6172 * (pow(10,n)-1) - 0.55 * n
打印 product
示例
下面是一个 C++ 程序,用于求解数列 5 + 55 + 555.....n 的和
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the
// the sum of series
int sumOfSeries(int n){
int product = 0.6172 * (pow(10,n)-1) - 0.55 * n;
return product;
}
int main(){
//Input
int n = 5;
//Function call to calculate the sum of series
cout << "Given Series; 5 + 55 + 555 + ..." << endl;
int answer = sumOfSeries(n);
//Print the answer
cout << "Sum up to 5 terms: " << answer<< endl;
return 0;
}
输出
Given Series; 5 + 55 + 555 + ... Sum up to 5 terms: 61716
分析
时间复杂度 − O(log n)。
程序的时间复杂度是对数级的,因为使用了幂函数。
空间复杂度 − O(1)
空间复杂度是常数级的,因为没有使用额外的空间。
结论
在本文中,我们讨论了求解数列 5+55+555+… 的前 n 项和的问题。输入中给出了 N。
我们使用等比数列求解了该数列,并编写了伪代码和 C++ 程序。
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP