首頁 >後端開發 >C++ >C/C++程式:計算以n的平方減去(n-1)的平方為第n項的序列的和

C/C++程式:計算以n的平方減去(n-1)的平方為第n項的序列的和

WBOY
WBOY轉載
2023-08-26 19:21:03920瀏覽

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) 和,

S n = T1 T2 T3 T4 ..... . T n

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

Example

的中文翻譯為:

範例

#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刪除