HDOJ 3123 GCC (数学)

来源:互联网 发布:汇编语言编程 编辑:程序博客网 时间:2024/06/10 13:06

GCC

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 4476    Accepted Submission(s): 1475


Problem Description
The GNU Compiler Collection (usually shortened to GCC) is a compiler system produced by the GNU Project supporting various programming languages. But it doesn’t contains the math operator “!”.
In mathematics the symbol represents the factorial operation. The expression n! means "the product of the integers from 1 to n". For example, 4! (read four factorial) is 4 × 3 × 2 × 1 = 24. (0! is defined as 1, which is a neutral element in multiplication, not multiplied by anything.)
We want you to help us with this formation: (0! + 1! + 2! + 3! + 4! + ... + n!)%m
 

Input
The first line consists of an integer T, indicating the number of test cases.
Each test on a single consists of two integer n and m.
 

Output
Output the answer of (0! + 1! + 2! + 3! + 4! + ... + n!)%m.

Constrains
0 < T <= 20
0 <= n < 10^100 (without leading zero)
0 < m < 1000000
 

Sample Input
110 861017
 

Sample Output
593846题意:给你一个n,然后求0到n的阶乘相加对m取余。思路:我们会发现当n大于等于m的时候,n!%m==0,所以只需要算比m小的数的阶乘之和对m取余就可以了,因为n的长度可达到100位,所以用字符串,另外多一个特判。总结:不能被那个数吓到,仔细写一下会发现没那么麻烦。。ac代码:
#include<stdio.h>#include<math.h>#include<string.h>#include<stack>#include<queue>#include<vector>#include<iostream>#include<algorithm>#define MAXN 1010000#define LL long long#define ll __int64#define INF 0xfffffff#define mem(x) memset(x,0,sizeof(x))#define PI acos(-1)#define mod 1000000007using namespace std;char s[110];int main(){int t,n,m,i,j,num,a;int cas=0;scanf("%d",&t);while(t--){scanf("%s%d",s,&m);int len=strlen(s);if(len>=7){num=m-1;LL ans=0;LL k=1;for(i=1;i<=num;i++){k=k*i%m;ans=(ans+k)%m;}printf("%lld\n",(ans+1)%m);continue;}num=0;for(i=0;i<len;i++)num=num*10+s[i]-'0';if(num>=m)num=m-1;LL ans=0;LL k=1;for(i=1;i<=num;i++){k=k*i%m;ans=(ans+k)%m;}printf("%lld\n",(ans+1)%m);}return 0;}


0 0
原创粉丝点击