級數 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