首页  >  文章  >  后端开发  >  C/C++程序:计算以n的平方减去(n-1)的平方为第n项的序列的和

C/C++程序:计算以n的平方减去(n-1)的平方为第n项的序列的和

WBOY
WBOY转载
2023-08-26 19:21:03891浏览

C/C++程序:计算以n的平方减去(n-1)的平方为第n项的序列的和

数学中有很多类型的级数,可以在C编程中轻松解决。该程序是在 C 程序中求级数的以下总和。

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

求级数所有项的总和,即 Sn mod (109 + 7) 和,

Sn = T 1 + T2 + T3 + T4 + ...... + Tn

Input: 229137999
Output: 218194447

说明

Tn可以表示为2n-1来得到

正如我们知道,

=> 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

示例

的中文翻译为:

示例

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

以上是C/C++程序:计算以n的平方减去(n-1)的平方为第n项的序列的和的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除