Description
You are given a recurrent formula for a sequence f:
f( n) = 1 + f(1) g(1) + f(2) g(2) + … + f( n−1) g( n−1),
where g is also a recurrent sequence given by formula
g( n) = 1 + 2 g(1) + 2 g(2) + 2 g(3) + … + 2 g( n−1) − g( n−1) g( n−1).
It is known that f(1) = 1, g(1) = 1. Your task is to find f( n) mod p.
Input
The input consists of several cases. Each case contains two numbers on a single line. These numbers are n (1 ≤ n ≤ 10000) and p (2 ≤ p ≤ 2·10 9). The input is terminated by the case with n = p = 0 which should not be processed. The number of cases in the input does not exceed 5000.
Output
Output for each case the answer to the task on a separate line.
Sample Input
input output
1 2 1
2 11 2
0 0
则有f(n)%p=n!%p=(n*(n-1)!)%p=((n%p)*((n-1)!%p))%p。可以设f(n)%p为m(n),则m(n)=(n*m(n-1))%p,这里的n%p=n是因为当n<p时,n%p必定等于n,当n=p时,理论上m(n)=0,此时m(n)=(n*m(n-1))%p=(p*m(n-1))%p=0,所以公式正确,后面大于p时m(n)也必定等于0,因为前面m(p)=0,所以m(p)*n=0,则m(n)=(n*m(p))%p=0,公式也正确,以此向后推,n%p直接取为n是没有问题的。
代码如下:
<span style="font-size:14px;">#include <iostream>
using namespace std;
int main()
{
long long n = 0;
long long p = 0;
long long m[10010];
m[1] = 1;
for(;;) {
cin>>n>>p;
if (n == 0 && p == 0)
break;
else {
for(int i = 2; i <= n; i++) {
m[i] = (m[i-1] * i) % p;
}
cout<<m[n]<<endl;
}
}
return 0;
}</span>