求系列 12, 105, 1008, 10011, ... 的 n 项之和
给定一个正整数n 。求数列前n 项的总和
12, 105, 1008, 10011, …..
例子:
Input: n = 4
Output: 11136
Input: n = 7
Output: 11111187
方法:
该序列是通过使用以下模式形成的。对于任何值 N-
上述解决方案可以通过以下一系列步骤得出:
Given Series-
12 + 105 + 1008 + 10011 +…….
10 + 2 + 100 + 5 + 1000 + 8 + 10000 + 11 +……..
(10 + 100 + 1000 + 10000+……) + (2 + 5 + 8 + 11+……) -(1)
The first term in the above equation is Geometric progression and the second term is Arithmetic progression.
G.P. =
where a is the first term a, r is the common ratio and n is the number of terms.
A.P. =
where a is the first term a, a is the common difference and n is the number of terms.
So after substituting values in equation of G.P. and A.P. and substituting corresponding equations in equation (1) we get,
So,
插图:
Input: n = 4
Output: 11136
Explanation:
This gives ans 11136.
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
#define ll long long
using namespace std;
// Function to return sum of
// N term of the series
ll findSum(ll n)
{
ll x = 10 * (pow(10, n) - 1) / 9;
ll y = n * (3 * n + 1) / 2;
return x + y;
}
// Driver Code
int main()
{
ll n = 4;
cout << findSum(n);
return 0;
}
Java
// Java program to implement
// the above approach
class GFG
{
// Function to return sum of
// N term of the series
static int findSum(int n) {
int x = (int)(10 * (Math.pow(10, n) - 1) / 9);
int y = n * (3 * n + 1) / 2;
return x + y;
}
// Driver Code
public static void main(String args[]) {
int n = 4;
System.out.println(findSum(n));
}
}
// This code is contributed by saurabh_jaiswal.
Python3
# Python program to implement
# the above approach
# include
# define ll long long
# Function to return sum of
# N term of the series
def findSum(n):
x = 10 * ((10 ** n) - 1) / 9
y = n * (3 * n + 1) / 2
return int(x + y)
# Driver Code
n = 4
print(findSum(n))
# This code is contributed by saurabh_jaiswal.
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Function to return sum of
// N term of the series
static int findSum(int n) {
int x = (int)(10 * (Math.Pow(10, n) - 1) / 9);
int y = n * (3 * n + 1) / 2;
return x + y;
}
// Driver Code
public static void Main()
{
int n = 4;
Console.Write(findSum(n));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
11136
时间复杂度: O(1)
辅助空间: O(1)