Series summation if T(n) is given and n is very large
Given a sequence whose nth term is
T(n) = n2 – (n – 1)2
The task is to evaluate the sum of first n terms i.e.
S(n) = T(1) + T(2) + T(3) + … + T(n)
Print S(n) mod (109 + 7).
Examples:
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
Approach: If we try to find out some initial terms of the sequence by putting n = 1, 2, 3, … in T(n) = n2 – (n – 1)2, we find the sequence 1, 3, 5, …
Hence, we find an A.P. where first term is 1 and d (common difference between consecutive
terms) is 2.
The formula for the sum of n terms of A.P is
S(n) = n / 2 [ 2 * a + (n – 1) * d ]
where a is the first term.
So, putting a = 1 and d = 2, we get
S(n) = n2
.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define ll long int
#define MOD 1000000007
int sumOfSeries( int n)
{
ll ans = (ll) pow (n % MOD, 2);
return (ans % MOD);
}
int main()
{
int n = 10;
cout << sumOfSeries(n);
return 0;
}
|
Java
class GFG
{
public static final int MOD = 1000000007 ;
static int sumOfSeries( int n)
{
int ans = ( int )Math.pow(n % MOD, 2 );
return (ans % MOD);
}
public static void main(String[] args)
{
int n = 10 ;
System.out.println(sumOfSeries(n));
}
}
|
Python3
from math import pow
MOD = 1000000007
def sumOfSeries(n):
ans = pow (n % MOD, 2 )
return (ans % MOD)
if __name__ = = '__main__' :
n = 10
print ( int (sumOfSeries(n)))
|
C#
using System;
class GFG
{
const int MOD = 1000000007;
static int sumOfSeries( int n)
{
int ans = ( int )Math.Pow(n % MOD, 2);
return (ans % MOD);
}
public static void Main()
{
int n = 10;
Console.Write(sumOfSeries(n));
}
}
|
PHP
<?php
$GLOBALS [ 'MOD' ] = 1000000007;
function sumOfSeries( $n )
{
$ans = pow( $n % $GLOBALS [ 'MOD' ], 2);
return ( $ans % $GLOBALS [ 'MOD' ]);
}
$n = 10;
echo sumOfSeries( $n );
?>
|
Javascript
<script>
let MOD = 1000000007;
function sumOfSeries(n)
{
let ans = Math.pow(n % MOD, 2);
return (ans % MOD);
}
let n = 10;
document.write(sumOfSeries(n));
</script>
|
Time Complexity: O(1) because calculation square of a number using pow function takes constant time.
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
03 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...