给定一个序列,其第n项是
T(n) = n2 – (n – 1)2
任务是评估前n个项的总和,即
S(n) = T(1) + T(2) + T(3) + … + T(n)
打印S(n)mod(10 9 + 7) 。
例子:
Input: n = 3
Output: 9
S(3) = T(1) + T(2) + T(3) = (12 – 02) + (22 – 12) + (32 – 22) = 1 + 3 + 5 = 9
Input: n = 10
Output: 100
方法:如果我们尝试通过将n = 1、2、3,…放入T(n)= n 2 –(n – 1) 2来找出序列的某些初始项,则会找到序列1、3、5 ,…
因此,我们找到第一个项为1和d的AP(连续项之间的共同差
项)是2 。
AP的n个项之和的公式为
S(n) = n / 2 [ 2 * a + (n – 1) * d ]
其中a是第一项。
因此,将a = 1和d = 2 ,我们得到
S(n) = n2
。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
#define ll long long int
#define MOD 1000000007
// Function to return the sum
// of the given series
int sumOfSeries(int n)
{
ll ans = (ll)pow(n % MOD, 2);
return (ans % MOD);
}
// Driver code
int main()
{
int n = 10;
cout << sumOfSeries(n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
public static final int MOD = 1000000007;
// Function to return the sum
// of the given series
static int sumOfSeries(int n)
{
int ans = (int)Math.pow(n % MOD, 2);
return (ans % MOD);
}
// Driver code
public static void main(String[] args)
{
int n = 10;
System.out.println(sumOfSeries(n));
}
}
// This code is contributed by Code_Mech.
Python3
# Python 3 implementation of the approach
from math import pow
MOD = 1000000007
# Function to return the sum
# of the given series
def sumOfSeries(n):
ans = pow(n % MOD, 2)
return (ans % MOD)
# Driver code
if __name__ == '__main__':
n = 10
print(int(sumOfSeries(n)))
# This code is contributed by
# Surendra_Gangwar
C#
// C# implementation of the approach
using System;
class GFG
{
const int MOD = 1000000007;
// Function to return the sum
// of the given series
static int sumOfSeries(int n)
{
int ans = (int)Math.Pow(n % MOD, 2);
return (ans % MOD);
}
// Driver code
public static void Main()
{
int n = 10;
Console.Write(sumOfSeries(n));
}
}
// This code is contributed
// by Akanksha Rai
PHP
输出:
100