1. 程式人生 > >SPOJ DCEPC11B - Boring Factorials 費馬小定理

SPOJ DCEPC11B - Boring Factorials 費馬小定理

pri med www. while mat const res 取余 multi

題目鏈接: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

#math

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
6
Constraints:

1 <= T <= 1000

1 < P <= 2*10^9

1 <= N <= 2*10^9

Abs(N-P) <= 1000

SPOJ DCEPC11B - Boring Factorials 費馬小定理