SPOJ DCEPC11B - Boring Factorials 费马小定理
题目链接:http://www.spoj.com/problems/DCEPC11B/
题目大意:求N!对P取余的结果。P是素数,并且abs(N-P)<=1000。
解题思路:wiki-费马小定理:
Fermat's little theorem states that if p is a prime number, then for any integer a, the number a p − a is an integer multiple of p. In the notation of modular arithmetic, this is expressed as
For example, if a = 2 and p = 7, 27 = 128, and 128 − 2 = 7 × 18 is an integer multiple of 7.
If a is not divisible by p, Fermat's little theorem is equivalent to the statement that a p − 1 − 1 is an integer multiple of p, or in symbols
For example, if a = 2 and p = 7 then 26 = 64 and 64 − 1 = 63 is thus a multiple of 7.
我们设 x = N!,那么由费马小定理:x * (n+1) * (n+2) * ... * (p-1) % p = p - 1.而(n+1) * (n+2) * ... * (p-1) % p 可以计算得到,那么有:
a * x % p = p - 1 即 a * x = k*p + p - 1 然后使用扩展欧几里得算法计算出x即可。
注意P<=N为0
代码:
1 ll n, p; 2 3 ll ext_gcd(ll a, ll b, ll &d, ll &x, ll &y){ 4 if(!b) { 5 d = a; x = 1; y = 0; 6 } 7 else{ 8 ext_gcd(b, a % b, d, y, x); y -= x * (a / b); 9 } 10 } 11 void solve(){ 12 if(p <= n) { 13 cout << 0 << endl; 14 return; 15 } 16 ll a = 1; 17 for(int i = n + 1; i <= p - 1; i++){ 18 a *= i; 19 a %= p; 20 } 21 ll b = p, d, x, y; 22 ext_gcd(a, b, d, x, y); 23 x *= (p - 1) / d; 24 if(x < 0) x += (abs(x) / p + 1) * p; 25 cout << x % p << endl; 26 } 27 int main(){ 28 ios::sync_with_stdio(false); 29 int t; 30 cin >> t; 31 while(t--){ 32 cin >> n >> p; 33 solve(); 34 } 35 }
题目:
DCEPC11B - Boring Factorials
Sameer and Arpit want to overcome their fear of Maths and so they have been recently practicing Maths problems a lot. Aman, their friend has been helping them out. But as it goes, Sameer and Arpit have got bored of problems involving factorials. Reason being, the factorials are too easy to calculate in problems as they only require the residue modulo some prime and that is easy to calculate in linear time. So to make things interesting for them, Aman - The Mathemagician, gives them an interesting task. He gives them a prime number P and an integer N close to P, and asks them to find N! modulo P. He asks T such queries.
Input
First line contains an integer T, the number of queries asked.
Next T lines contains T queries of the form “N P”. (quotes for clarity)
Output
Output exactly T lines, containing N! modulo P.
Example
Input: 3 2 5 5 11 21 71 Output: 2 10 6Constraints:
1 <= T <= 1000
1 < P <= 2*10^9
1 <= N <= 2*10^9
Abs(N-P) <= 1000