(a+b)%m=[(a%m)+(b%m)]%m
(a*b)%m=[(a%m)*(b%m)]%m
所以(0!+1!+2!+.....+n!)%m=[(0!%m+1!%m)%m+(1!%m)*(2%m)%m}%m.........到K>=n时,K!%m=0
所以分为n>=m和n<m两种情况
#include <stdio.h> #include <string.h> #include <math.h> char s[101]; int main() { int t, n, m; scanf("%d",&t); while (t--) { scanf("%s %d", s, &m); long long a = 1, b = 1; int n = 0, i; for (i=strlen(s)-1; i>=0; i--) { n += (s[i]-'0')*b; if (n>=m) break; b *= 10; } b = 1; if (n<m) for (i=1;i<=n; i++) { b = (b*i)%m; a = (a+b)%m; } else for (i=1; i<m; i++) { b = (b*i)%m; a = (a+b)%m; } printf("%I64d\n", a%m); } system("pause"); return 0; }