We are given an integer n and n-th term in a series as expressed below:

T_{n}= n^{2}- (n-1)^{2}

We need to find S_{n} mod (10^{9} + 7), where S_{n} is the sum of all of the terms of the given series and,

S_{n}= T_{1}+ T_{2}+ T_{3}+ T_{4}+ ...... + T_{n}

Examples:

Input : 229137999 Output : 218194447 Input : 344936985 Output : 788019571

Let us do some calculations, before writing the program. T_{n} can be reduced to give 2n-1 . Let’s see how:

Given, T_{n}= n^{2}- (n-1)^{2}Or, T_{n}= n^{2}- (1 + n^{2}- 2n) Or, T_{n}= n^{2}- 1 - n^{2}+ 2n Or, T_{n}= 2n - 1.

Now, we need to find ∑T_{n}.

∑T_{n} = ∑(2n – 1)

We can simplify the above formula as,

∑(2n – 1) = 2*∑n – ∑1

Or, ∑(2n – 1) = 2*∑n – n.

Where, ∑n is the sum of first n natural numbers.

We know the sum of n natural number = n(n+1)/2.

Therefore, putting this value in the above equation we will get,

∑T_{n} = (2*(n)*(n+1)/2)-n = n^{2}

Now the value of n^{2} can be very large. So instead of direct squaring n and taking mod of the result. We will use the property of modular multiplication for calculating squares:

(a*b)%k = ((a%k)*(b%k))%k

`// Java program to find sum of given ` `// series. ` ` ` `public` `class` `FINDSUM { ` ` ` ` ` `static` `long` `mod = ` `1000000007` `; ` ` ` ` ` `public` `static` `long` `findSum(` `long` `n) ` ` ` `{ ` ` ` `return` `((n % mod) * (n % mod)) % mod; ` ` ` `} ` ` ` ` ` `public` `static` `void` `main(String[] args) ` ` ` `{ ` ` ` `long` `n = ` `229137999` `; ` ` ` `System.out.print(findSum(n)); ` ` ` `} ` `} ` ` ` `// Contributed by _omg ` |

*chevron_right*

*filter_none*

**Output:**

218194447

Please refer complete article on Find sum of Series with n-th term as n^2 – (n-1)^2 for more details!

## Recommended Posts:

- Program to find Nth term of the series 3, 6, 18, 24, ...
- Program to find Nth term of the series 2, 4, 3, 4, 15...
- Find Nth term of the series 5, 13, 25, 41, 61...
- Find Nth term of the series 1, 1, 2, 6, 24...
- Java Program for nth multiple of a number in Fibonacci Series
- Java Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!
- Program to find the sum of the series (1/a + 2/a^2 + 3/a^3 + ... + n/a^n)
- Java Program for nth Catalan Number
- Java Program for Print Number series without using any loop
- Java Program for Program to find area of a circle
- Java Program to Find sum of even factors of a number
- Java Program to Find minimum sum of factors of number
- Java Program to find sum of array
- 3 Different ways to print Fibonacci series in Java
- Java Program for Program to calculate area of a Tetrahedron
- Java Program for Program for array rotation
- Program for Find sum of odd factors of a number
- Java Program for Range sum queries without updates
- Java Program for cube sum of first n natural numbers
- Java Program for Sum of squares of first n natural numbers