为什么会接触到这个数学知识?
还得从一个OJ题目说起。。。。。。
Problem K
Description
FunnyAC likes mathematics very much. He thinks mathematics is very funny and beautiful.When he solved a math problem he would be very happy just like getting accepted in ACM.Recently, he find a very strange problem.Everyone know that the sum of sequence from 1 to n is n*(n + 1)/2. But now if we create a sequence which consists of the sum of sequence from 1 to n. The new sequence is 1, 1+ 2, 1+2+3, …. 1+2+…+n. Now the problem is that what is the sum of the sequence from1 to 1+2+…+n .Is it very simple? I think you can solve it. Good luck!
Input
The first line contain an integer T .Then T cases followed. Each case contain an integer n (1 <= n <= 10000000).
Output
For each case,output the sum of first n items in the new sequence. Because the sum is very larger, so output sum % 20090524.
这个题如果使用递归直接算的话,数据绝对会爆掉。。。。。。。
但是,可以自己推出公式 Sn = n(n+1)(n+2)/6;
然而数据依然爆掉。。。。。。
只能求助汝佳哥了,查到紫书有个同余与模算术这节。
公式如下
(a+b) mod n=((a mod n)+(b mod n)) mod n
(a-b) mod n=((a mod n)-(b mod n)+n) mod n
ab mod n=(a mod n)(b mod n) mod n
#include int main()
{
int t;
scanf("%d",&t);
while(t--)
{
longlong n;
scanf("%I64d",&n);
if(n == 1)
{
printf("1
");
continue;
}
longlong ans = (n*(n+1))%(20090524*6);
ans = (ans*(n+2)/6)%20090524;
printf("%lld
",ans);
}
return0;
}
成功解决,ok。