数学知识 同余与模算术

来源:互联网 发布:淘宝剑三金币 编辑:程序博客网 时间:2024/06/05 22:55

为什么会接触到这个数学知识?
还得从一个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 <stdio.h> int main() {     int t;     scanf("%d",&t);     while(t--)     {         long long n;         scanf("%I64d",&n);         if(n == 1)         {             printf("1\n");             continue;         }         long long ans = (n*(n+1))%(20090524*6);         ans = (ans*(n+2)/6)%20090524;         printf("%lld\n",ans);     }     return 0; }

成功解决,ok。

0 0