Formula
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 306 Accepted Submission(s): 128
Problem Description
f(n)=(∏i=1nin−i+1)%1000000007
You are expected to write a program to calculate f(n) when a certain n is given.
You are expected to write a program to calculate f(n) when a certain n is given.
Input
Multi test cases (about 100000), every case contains an integer n in a single line.
Please process to the end of file.
[Technical Specification]
1≤n≤10000000
Please process to the end of file.
[Technical Specification]
1≤n≤10000000
Output
For each n,output f(n) in a single line.
Sample Input
2 100
Sample Output
2 148277692
递推关系式挺简单的。
官方题解:
找规律
f(1)=1
f(2)=1*1*2=(1)*(1*2)=1!*2!
f(3)=1*1*1*2*2*3=(1)*(1*2)*(1*2*3)=1!*2!*3!
式子可以简化为 f(n)=∏i=1n(n!)%MOD,直接打表不行,会超内存,可以对数据进行离线处理。排好序之后从小到大暴力。ClogC+10000000 ,C为case数目。
我的解法
用一个数组存整百的结果,再用个数组存整百的阶乘的结果。这样每个查询就可以根据除以100找到对应的整百的结果,再最多递推99个就可以出结果。
代码:
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; const int mod=1000000007; long long a[100010]; long long b[100010]; int main() { long long help=1; long long ans0=1,ans1=1; a[0]=1; b[0]=1; for(int i=1;i<=10000000;i++) { ans1=(ans0*help)%mod; help = help*(i+1)%mod; if(i%100==0) { a[i/100]=ans1; b[i/100]=help; } ans0=ans1; } int n; while(~scanf("%d",&n)) { int temp=n/100; // printf("%I64d\n",a[temp]); ans0=ans1=a[temp]; help=b[temp]; for(int i=temp*100+1;i<=n;i++) { ans1=(ans0*help)%mod; help = help*(i+1)%mod; ans0=ans1; } printf("%I64d\n",ans1); } return 0; }