Home > Backend Development > C++ > C/C++ program: Calculate the sum of the sequence with n squared minus (n-1) squared as the nth item

C/C++ program: Calculate the sum of the sequence with n squared minus (n-1) squared as the nth item

WBOY
Release: 2023-08-26 19:21:03
forward
950 people have browsed it

C/C++ program: Calculate the sum of the sequence with n squared minus (n-1) squared as the nth item

There are many types of series in mathematics which can be solved easily in C programming. This program is to find the sum of following of series in C program.

T<sub>n</sub> = n<sup>2</sup> - (n-1)<sup>2</sup>
Copy after login

Find the sum of all of the terms of series as Sn mod (109 7) and,

Sn = T1 T2 T3 T4 ...... Tn

Input: 229137999
Output: 218194447
Copy after login

Explanation

Tn can be expressed as 2n-1 to get it

As we know ,

=> Tn = n2 - (n-1)2
=>Tn = n2 - (1 + n2 - 2n)
=>Tn = n2 - 1 - n2 + 2n
=>Tn = 2n - 1.
find &sum;Tn.
&sum;Tn = &sum;(2n &ndash; 1)
Reduce the above equation to,
=>&sum;(2n &ndash; 1) = 2*&sum;n &ndash; &sum;1
=>&sum;(2n &ndash; 1) = 2*&sum;n &ndash; n.
here, &sum;n is the sum of first n natural numbers.
As known the sum of n natural number &sum;n = n(n+1)/2.
Now the equation is,
&sum;Tn = (2*(n)*(n+1)/2)-n = n2
The value of n2 can be large. Instead of using n2 and take the mod of the result.
So, using the property of modular multiplication for calculating n2:
(a*b)%k = ((a%k)*(b%k))%k
Copy after login

Example

的中文翻译为:

示例

#include <iostream>
using namespace std;
#define mod 1000000007
int main() {
   long long n = 229137999;
   cout << ((n%mod)*(n%mod))%mod;
   return 0;
}
Copy after login

The above is the detailed content of C/C++ program: Calculate the sum of the sequence with n squared minus (n-1) squared as the nth item. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template